Reputation: 521
I am following the The Swift Programming Language book to investigate strong reference cycle. One of the examples that should be working cannot be compiled in Xcode. I don't understand why the code is broken.
On this chapter, there is an example that looks like this:
When I try to compile this code in Xcode the this error was thrown: 'self' used before all stored properties are initialized. However, I think it should have been able to compile because I set capitalCity to be Implicitly Unwrapped Optionals that is nil by default, so after I set self.name = name all stored properties should be already properly set.
What do I miss here? What changes are needed to make the code compile?
Thanks in advance!
Upvotes: 1
Views: 392
Reputation: 952
Just Change (let to var)
let capitalCity: City!
To
var capitalCity: City!
This happens, probably, because it cannot be a constant value, since we set it up during init.
update:
I have NO idea why I'm down voted!. This is the example from the book, and does NOT compile. But if you change let to var as I said, you'll get it work!
Who can offer here a code modification, so that the code FROM THE BOOK can be compiled!?
I can only admit that I shouldn't write about setting up let in initializer, but I think it's obvious I didn't mean that you cannot set up regular let in initialiser
Upvotes: 1
Reputation: 8216
let
statements don't have default initialization of optionals to nil, because otherwise writing let foo:Bar!
would give you a foo
that was always nil and you couldn't initialize it in a subsequent statement.
The reason var
is appropriate is that you want default initialization to nil to occur so you can initialize your City
object with the self reference in order to finally initialize your actual capitalCity
value which is really double initialization.
The code has a circular class dependency by design, so this is a side effect of that design.
This behavior of let
is new in Swift 1.2, try the example in Xcode 6.2 or earlier and you will find that it compiles.
Upvotes: 4
Reputation: 29896
As the initializer has not set up the object yet, you cannot initialise another one with it.
You need to initialize the city and then set the property.
Upvotes: 2