Init from string and unit lowercased init subscript
This commit is contained in:
@@ -236,7 +236,7 @@ public enum Unit: String, CaseIterable, CustomStringConvertible, Codable,
|
||||
public var description: String { rawValue }
|
||||
|
||||
public static subscript(rawValue: String) -> Unit? {
|
||||
.init(rawValue: rawValue)
|
||||
.init(rawValue: rawValue.lowercased())
|
||||
}
|
||||
|
||||
public static subscript(category: UnitCategory) -> [Unit] {
|
||||
@@ -273,6 +273,22 @@ public struct UnitValue<ValueType: ConvertibleToDouble>:
|
||||
self.unit = unit
|
||||
}
|
||||
|
||||
/// Initializes from a String. eg. 100 mL
|
||||
public init?(from s: String) {
|
||||
let splitted = s.split(separator: " ")
|
||||
guard splitted.count == 2 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let unit = Unit[String(splitted[1])],
|
||||
let value = Double(splitted[0]) as? ValueType
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.init(value: value, unit: unit)
|
||||
}
|
||||
|
||||
// MARK: Conversion Logic
|
||||
/// Converts the current UnitValue to a specified target unit.
|
||||
/// - Parameter targetUnit: The unit to convert to.
|
||||
|
||||
Reference in New Issue
Block a user