初始化类的实例时,序列是什么? [英] When an instance of a class is initialized, what is the sequence?

查看:92
本文介绍了初始化类的实例时,序列是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我对这里发生的序列感到困惑(我完全意识到 var 让)。但是,为什么我会收到该错误?

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?


  • 如果我使用的是 init 方法,那并不意味着我没有使用
    的默认参数?

  • 为什么不能用另一个参数更改默认常量?

  • 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?

推荐答案

您不能多次分配let变量-但是,您可以定义它并使它不初始化。然后,在您的 init 方法中,您可以将 nobody 作为的默认值。 agent 参数。

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"

正如亚历山大在下面的注释中所建议的那样,如果init方法中的参数过多,则默认值可能会有些混乱。考虑创建一个单独的初始化方法来设置默认值。

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

这篇关于初始化类的实例时,序列是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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