Because property observers observe and respond to changes, why they cannot observe and respond to change in a property wrapper?
There happens to be an error
If that being so, the willSet and didSet property observers would change to func.
Someone tell me if we can do that or not?
Code Block import Foundation @propertyWrapper struct Property { private var number: Int = 0 private var maximum: Int = 0 var wrappedValue: Int { get { return number } set { number = min(newValue, maximum) } } init() { maximum = 12 number = 0 } init(wrappedValue: Int) { maximum = 12 number = min(wrappedValue, maximum) } init(wrappedValue: Int, maximum: Int) { self.maximum = maximum number = min(wrappedValue, maximum) } willSet() {} didSet() {} } struct SmallRectangle { @Property(wrappedValue: 12, maximum: 25) var _height: Int @Property(wrappedValue: 12, maximum: 25) var _width: Int } var smallRectangle = SmallRectangle() smallRectangle._height = 18 print(smallRectangle._height)
There happens to be an error
at line 29 and 30."Expected 'func' keyword in instance method declaration"
If that being so, the willSet and didSet property observers would change to func.
Someone tell me if we can do that or not?
You cannot.if we can do that or not
willSet or didSet are tightly coupled with stored property, and modify the implicitly generated setter for the property.
Putting willSet or didSet in a propertyWrapper has no meaning in property observers of Swift.
Declaring a stored property with observers like this:
Code Block var storedProperty: SomeType { willSet { //...`willSet` statements } didSet { //...`didSet` statements } }
is nearly equivalent to the following set of declarations:
Code Block var _storedProperty: SomeType //<- This actually is not a `property` and cannot be accessed even from private context var storedProperty: SomeType { //<- This actually is a computed property get { return _storedProperty } set { do { //...`willSet` statements } _storedProperty = newValue do { //...`didSet` statements } } }
The keywords willSet and didSet are only valid in the declaration of stored properties and affect the behavior of setter.
There's no magic feature to observe and respond to changes.
So, if you want to add sort of observing feature to your property wrapper, try modifying the setter of wrappedValue.