From the Swift docs:
A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly. This approach avoids confusion about how the value is accessed in different contexts and simplifies the property’s declaration into a single, definitive statement.
And:
The willSet and didSet observers for totalSteps are called whenever the property is assigned a new value. This is true even if the new value is the same as the current value.
There's no exact analogy to backing variables integrated into Swift. You can replicate Objective-C properties (see nhgrif's answer). That approach would be foreign in Swift, though, and might be difficult for future programmers to understand. If you don't want to do that, you could either move your didSet
code to a separate function…
class User : NSObject {
var name: String = ""
func setNameAndPrint(name newName : String) {
name = newName
print("newName = " + name)
}
}
let user = User()
user.name = "Aaron" // doesn't print anything
user.setNameAndPrint(name: "Zhao Wei") // prints "newName = Zhao Wei"
… or you could write more explicit code to mimic this behavior …
class User : NSObject {
var printNameAfterSetting = true
var name: String = "" {
didSet {
if printNameAfterSetting {
print("newName = " + name)
} else {
printNameAfterSetting = true
}
}
}
}
let user = User()
user.printNameAfterSetting = false
user.name = "Aaron" // prints nothing
user.name = "Zhao Wei" //prints "newName = Zhao Wei"
This example uses a bool, but you could use an enum or other type to represent more complex logic depending on your use case.