Swift自定义属性包装器(property wrapper)

//自定义一个汇率转化的修饰语
//案例来自swiftUIAndCombine

@propertyWrapper struct Converter {
    let from: String
    let to: String
    let rate: Double
    var value:Double
    var wrappedValue: String {
        get {"\(from) \(value)"}//包装后的值永远来自参数from和参数value的字符串拼接
        set {value = Double(newValue) ?? -1}//每当设置该包装后的值的时候将value的值设置为newValue
    }
    var projectedValue: String {
        return "\(to) \(value * rate)"
    }
    
    init(initialValue: String,
         from: String,
         to: String,
         rate: Double) 
    {
        self.rate = rate
        self.value = 0
        self.from = from
        self.to = to
        self.wrappedValue = initialValue
    }
}
@Converter(initialValue: "100", from: "USD", to: "CNY", rate: 6.88) var usd_cny
@Converter(initialValue: "100", from: "CNY", to: "EUR", rate: 0.13) var cny_eur
print("\\(usd_cny) = \\(\$usd_cny)") print("\\(cny_eur) = \\(\$cny_eur)")
!" 输出:
!" USD 100.0 = CNY 688.0 !" CNY 100.0 = EUR 13.0
usd_cny = "324.3"
!" USD 324.3 = CNY 2231.184

你可能感兴趣的:(swift)