@propertyWrapper structTwelveOrLess{ privatevar number: Int // wrappedValue变量的名字是固定的 var wrappedValue: Int { get { return number } set { number = min(newValue, 12) } } init() { self.number = 0 } }
structSmallRectangle{ @TwelveOrLessvar height: Int @TwelveOrLessvar width: Int }
var rectangle = SmallRectangle() print(rectangle.height) // 0
@propertyWrapper structSmallNumber{ privatevar maximum: Int privatevar number: Int var wrappedValue: Int { get { return number } set { number = min(newValue, maximum) } } init() { maximum = 12 number = 0 } init(wrappedValue: Int) { print("init(wrappedValue:)") maximum = 12 number = min(wrappedValue, maximum) } init(wrappedValue: Int, maximum: Int) { print("init(wrappedValue:maximum:)") self.maximum = maximum number = min(wrappedValue, maximum) } }
使用了 @SmallNumber 但没有指定初始化值
1 2 3 4 5 6 7
structZeroRectangle{ @SmallNumbervar height: Int @SmallNumbervar width: Int }
var zeroRectangle = ZeroRectangle() print(zeroRectangle.height, zeroRectangle.width) // 0 0
使用了 @SmallNumber ,并指定初始化值
这里会调用 init(wrappedValue:) 方法
1 2 3 4 5 6 7
structUnitRectangle{ @SmallNumbervar height: Int = 1 @SmallNumbervar width: Int = 1 }
var unitRectangle = UnitRectangle() print(unitRectangle.height, unitRectangle.width) // 1 1
使用@SmallNumber,并传参进行初始化
这里会调用 init(wrappedValue:maximum:) 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
structNarrowRectangle{ // 报错:Extra argument 'wrappedValue' in call // @SmallNumber(wrappedValue: 2, maximum: 5) var height: Int = 1 // 这种初始化是可以的,调用 init(wrappedValue:maximum:) 方法 // @SmallNumber(maximum: 9) var height: Int = 2 @SmallNumber(wrappedValue: 2, maximum: 5) var height: Int @SmallNumber(wrappedValue: 3, maximum: 4) var width: Int }
var narrowRectangle = NarrowRectangle() print(narrowRectangle.height, narrowRectangle.width) // 2 3