我把自己变成了一个playground --熟悉房产包装的榜样.
以下代码:
import Foundation
@propertyWrapper
struct Price {
private var price: Double
init() {
self.price = 0.0
}
var wrappedValue: Double {
get {
return self.price
}
set {
if newValue < 0.0 {
self.price = 0.0
} else if newValue > 10_000 {
return
} else {
self.price = newValue
}
}
}
}
struct Article {
var vendor: String
var name: String
@Price var price: Double
}
var display = Article(vendor: "Asus", name: "X127", price: 139.0)
/*
expression failed to parse:
error: Playground.playground:33:60: error: cannot convert value of type 'Double' to expected argument type 'Price'
var display = Article(vendor: "Asus", name: "X127", price: 139.0)
*/
print("\(display.vendor) Display costs \(display.price) Euro")
如果我用...
var display = Article(vendor: "Asus", name: "X127")
display.price = 129.99
print("\(display.vendor) Display costs \(display.price) Euro")
// Asus Display costs 129.99 Euro
...那么它就运行得很好.
What I'm I doing wrong with the constructor-initialization? What's the correct way to initialize the wrapper property?个
What is going wrong within the first example in general?个