问题
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
initmethod, 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