When an instance of a class is initialized, what is the sequence?

被刻印的时光 ゝ 提交于 2020-01-06 18:05:15

问题


class Actor {
    let agent: String? = "nobody"

    init(agent: String){
        self.agent = agent // error: immutable value 'self.agent' may only be initialized once
    }
}

let John = Actor(agent: "xyz")

I'm confused about the sequence that is happening here (I'm fully aware of the differences between var and let). But why do I get that error?

  • If I'm using the init method, then doesn't that mean I'm not using the default parameter?
  • Why can't I change the default constant with another one?

回答1:


You cannot assign a let variable more than once - however, you can define it and leave it uninitialized. Then in your init method, you can have "nobody" as the default value for the agent argument.

class Actor {
    let agent: String

    init(agent: String = "nobody"){
        self.agent = agent
    }
}

print(Actor().agent) // "nobody"
print(Actor(agent: "xyz").agent) // "xyz"

As Alexander suggested in the comments below, if you have too many arguments in your init method, default values can get a little messy. Consider creating a separate init method that sets the default values.

class Actor {
    let agent: String
    ...

    init() {
        self.agent = "nobody"
        ...
    }

    init(agent: String, ...){
        self.agent = agent
        ...
    }
}


来源:https://stackoverflow.com/questions/42145422/when-an-instance-of-a-class-is-initialized-what-is-the-sequence

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