#39;self#39; used before all stored properties are initialized(self 在所有存储的属性被初始化之前使用)
问题描述
我正在处理 learn-swift playground 并在我学习该语言时将其升级到 Swift 2.0.以下代码(可能适用于早期版本的 Swift)现在会生成两个错误:在所有存储属性初始化之前使用'self'"和在初始化之前使用常量'self.capitalCity'"
I'm working through a learn-swift playground and upgrading it to Swift 2.0 as I learn the language. The following code (which likely worked with prior versions of Swift) now generates two errors: "'self' used before all stored properties are initialized" and "Constant 'self.capitalCity' used before initialized"
class Country
{
let name: String
let capitalCity: City!
init(name: String, capitalName: String)
{
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City
{
let name: String
unowned let country: Country
init(name: String, country: Country)
{
self.name = name
self.country = country
}
}
阅读回答类似的问题 我看到我可以将 let capitalCity: City!
更改为 var capitalCity: City!
并解决语法错误.
reading an answer to a similar question I see that I can change let capitalCity: City!
to var capitalCity: City!
and the syntax error is resolved.
我意识到在这个人为的例子中,一个国家的首都可以改变,所以这很好,但是如果有一个值真的是一个常数的情况......
I realize that in this contrived example a country's capital city can change, so that would be fine, but what if there were a case where the value really was a constant...
有什么方法可以解决语法错误,同时保持 capitalCity 不变?
Is there any way to resolve the syntax error while keeping capitalCity a constant?
推荐答案
在这种情况下,我建议您将属性设置为变量,但通过计算属性将其隐藏(使其看起来像常量):
In this case I would suggest you to make the property a variable but hiding it (make it seem like a constant) through a computed property:
class Country {
let name: String
private var _capitalCity: City!
var capitalCity: City {
return _capitalCity
}
init(name: String, capitalName: String) {
self.name = name
self._capitalCity = City(name: capitalName, country: self)
}
}
这篇关于'self' 在所有存储的属性被初始化之前使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'self' 在所有存储的属性被初始化之前使用
基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01