Skip to content

Instantly share code, notes, and snippets.

@nh7a
Created June 11, 2014 02:44
Show Gist options
  • Save nh7a/b2334c80a3f4db343987 to your computer and use it in GitHub Desktop.
Save nh7a/b2334c80a3f4db343987 to your computer and use it in GitHub Desktop.
property observer bug
class NumberString {
var number = 0
var string: String = "" {
didSet { number = string.toInt()! }
}
init(foo: String) {
string = foo // Will NOT cause didSet
}
init(bar: String) {
setString(bar)
}
func setString(foo: String) {
string = foo // Will cause didSet
}
}
var foo = NumberString(foo: "123") // number = 0
foo.string = "456" // number = 456
var bar = NumberString(bar: "789") // number = 789
@norio-nomura
Copy link

This behavior is noted in The Swift Programming Language: Properties as following:

willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.

@nh7a
Copy link
Author

nh7a commented Jun 11, 2014

Yes. But "string" property is initialized with "" already, therefore the line 8 isn't actually necessary to compile the code. (that's why the line 12 is possible without doing something like string = "").
If both initializers behave exactly the same, I can see it as consistent and not "a bug"

@norio-nomura
Copy link

I understand. It's mismatch between "var is initialized" and "it's in initializer".
Currently, following condition takes priority.

They are only called when the property’s value is set outside of an initialization context.

I guess these comes from two different side "What is required before calling func in initializer?" and "When can property be observable?".
It's interesting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment