在Swift中隐式解开Optionals似乎不起作用 [英] Implicitly Unwrapped Optionals in Swift does not seem to work

查看:124
本文介绍了在Swift中隐式解开Optionals似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究《 Swift编程语言》这本书,以研究强大的参考周期.无法正常工作的示例之一无法在Xcode中进行编译.我不明白为什么代码被破坏了.

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:

当我尝试在Xcode中编译此代码时,抛出此错误:在所有存储的属性初始化之前使用了'self'.但是,我认为它应该能够编译,因为我将capitalCity设置为默认情况下为nil隐式解包Optionals,因此在设置 self.name = name 之后,所有存储的属性都应该已经正确设置

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?

提前谢谢!

推荐答案

let语句没有可选的默认初始化为nil,因为否则编写let foo:Bar!会得到始终为nil的foo您无法在后续语句中对其进行初始化.

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.

var合适的原因是您希望默认初始化为nil,所以您可以使用自引用初始化City对象,以便最终初始化实际的capitalCity值,这实际上是两次初始化.

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.

let的此行为是Swift 1.2中的新增功能,请尝试在Xcode 6.2或更早版本中使用该示例,然后您会发现它可以编译.

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.

这篇关于在Swift中隐式解开Optionals似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆