I'm trying to implement RawRepresentable
on Measurement<UnitMass>
and UnitMass
in order to replace the following code with the @AppStorage
decorator:
var unitOfMeasure: UnitMass { get { AppSettings.defaults.string(forKey: "unitOfMeasure").flatMap { UnitMass.fromSymbol(rawValue: $0) }! } set { AppSettings.defaults.set(newValue.symbol, forKey: "unitOfMeasure") } } var weightOverwrite: Measurement<UnitMass> { get { .init(value: AppSettings.defaults.double(forKey: "weightOverwrite"), unit: unitOfMeasure) } set { AppSettings.defaults.set(newValue.value, forKey: "weightOverwrite") } }
How can I do this? I kinda achieved it using JSONEncoder/JSONDecoder:
extension Measurement: RawRepresentable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode(Measurement.self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), let result = String(data: data, encoding: .utf8) else { return "{}" } return result } }
But I fail to do it for UnitMass:
extension UnitMass: RawRepresentable { public init?(rawValue: String) { for unitMass in UnitMass.allCases where rawValue == unitLength.symbol { self = unitLength } return nil } }
I get Designated initializer cannot be declared in an extension of 'UnitMass'
. What am I doing wrong?
没有评论:
发表评论