Return from initializer without initializing all stored properties

后端 未结 5 1388

I have a simple class like this.

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

    init(id:          


        
5条回答
  •  孤街浪徒
    2020-12-05 13:17

    You need to explicitly set a value for email since it is a constant.

    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
            self.email = nil // <--------------
        }
    }
    

    Or as the others mentioned you can change email to a variable.

提交回复
热议问题