Created
June 11, 2014 02:44
-
-
Save nh7a/b2334c80a3f4db343987 to your computer and use it in GitHub Desktop.
property observer bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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"
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
This behavior is noted in The Swift Programming Language: Properties as following: