Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

ios - Return from initializer without initializing all stored properties

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

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

Return from initializer without initializing all stored properties

Why is that and how can I resolve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Related statements in the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...