Implicitly Unwrapped Optionals in Swift does not seem to work

女生的网名这么多〃 提交于 2020-01-05 08:22:11

问题


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!


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/30517167/implicitly-unwrapped-optionals-in-swift-does-not-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!