Return from initializer without initializing all stored properties

后端 未结 5 1385

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:18

    First of all make it clear that every let variable must be assigned value at declaration time. So your statements will be

    let id: Int  = 0
    let firstName: String = "test"
    let lastName: String = "Test"
    let email: String? = "Test"
    

    Secondly in classes, you must have to initialize variables or define them as optional types by either putting '?' or '!' with every variable. Like

    let id: Int!
    let firstName: String!
    let lastName: String!
    let email: String?
    

    or

    let id: Int?
    let firstName: String?
    let lastName: String?
    let email: String?
    

    But want to say you here that these variables will not be able to change as they are constants. so you must use var with these if you'r not passing value at time of declaration. Your final code in this case will be some kind of this

    var id: Int
    var firstName: String
    var lastName: String
    var email: String?
    

提交回复
热议问题