从初始化程序返回而不初始化所有存储的属性 [英] Return from initializer without initializing all stored properties

查看:445
本文介绍了从初始化程序返回而不初始化所有存储的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的简单类。

I have a simple class like this.

public class User {
    let id: Int
    let firstName: String
    let lastName: String
    let email: String?

    init(id: Int, firstName: String, lastName: String) {
        self.id = id
        self.firstName = firstName
        self.lastName = lastName
    }
}

这在以前的Swift版本中编译得很好。在Swift 1.2中,我得到以下编译错误。

This compiled just fine in previous Swift version. In Swift 1.2, I get the following compilation error.

从初始化程序返回而不初始化所有存储的属性

为什么会这样,我该如何解决?

Why is that and how can I resolve it?

推荐答案

如果属性是常量,那么创建时,您必须在适当位置或 init 方法初始化它,即使它是可选。如果您希望能够选择性地设置电子邮件,则应将 let 更改为 var 。换句话说,如果您没有在init方法或类主体中初始化变量,那么该变量必须是 var 可选

If a property is constant, so created with let, you have to initialize it in place or in the init method, even if it is an Optional. If you want to be able to set email optionally, you should change let to var. In other words, if you are not initializing a variable in either the init method or class body, then the variable must be both a var and an Optional.

docs


你可以在初始化期间的任何时刻为常量属性赋值,只要在初始化完成时将其设置为确定值即可。一旦为常量属性赋值,就无法进一步修改它。

You can assign a value to a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes. Once a constant property is assigned a value, it can’t be further modified.

对于类实例,只能在引入它的类初始化期间修改常量属性。它不能被子类修改。

For class instances, a constant property can only be modified during initialization by the class that introduces it. It cannot be modified by a subclass.

这篇关于从初始化程序返回而不初始化所有存储的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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