在初始化所有存储的属性之前使用“自我" [英] 'self' used before all stored properties are initialized

查看:148
本文介绍了在初始化所有存储的属性之前使用“自我"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过

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...

有什么办法可以在保持大写城市不变的情况下解决语法错误?

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)
    }
}

这篇关于在初始化所有存储的属性之前使用“自我"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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