Applies to:
- Xcode Extension
- Finder Extension
- Advanced Project Converter
- Offline Converter
Included in plans:
- Cloud
- Offline Converter
Swiftify now offers the option to generate `didSet` property observers. This option is turned on by default. To get more perspective, we can look at the conversion results with this option turned on/off with a sample Objective-C code.
Original Objective-C code:
Converted Swift code with this option turned on:
Converted Swift code with this option turned off:
To toggle this feature, open Preferences (⌘+,) => Converter and toggle the corresponding checkbox:
Implementation notes
While the code using
didSetobservers looks cleaner and more concise, beware of special cases when the generated Swift code may not behave 1:1 compared to the original Objective-C code:
- According to Apple's documentation:
The
willSet and
didSet observers provide a way to observe (and to respond appropriately) when the value of a variable or property is being set. The observers aren’t called when the variable or property is first initialized. Instead, they’re called only when the value is set outside of an initialization context.
That said, if a property was assigned from the initializer in your Objective-C code, the
didSet
observer in the translated Swift code might not get called at all. You are advised to review the converted code after the conversion, and, if needed, wrap the initialization code that assigns such a property inside a defer statement.
2. Currently, we only generate
didSet property observers when the property is assigned as the first line of the setter method. So far, we do not generate
willSetobservers if a property is assigned somewhere in the middle of the setter method (refer to this GitHub ticket for more details).
If you would like such support for
willSetobservers to be implemented, sign in with your Swiftify account and leave a comment explaining your use case below.
3.
didSet property observers are also generated for patterns where the property is assigned only if its value has changed (refer to this ticket for details). The Swift code inside the
didSet block will always be executed (even if the same value is assigned to the property).
Comments
0 comments
Please sign in to leave a comment.