Why convenience keyword is even needed in Swift?

后端 未结 6 938
后悔当初
后悔当初 2020-12-02 04:06

Since Swift supports method and initializer overloading, you can put multiple init alongside each other and use whichever you deem convenient:

c         


        
6条回答
  •  青春惊慌失措
    2020-12-02 04:36

    Mostly clarity. From you second example,

    init(name: String) {
        self.name = name
    }
    

    is required or designated. It has to initialize all your constants and variables. Convenience initializers are optional, and can typically be used to make initializing easier. For example, say your Person class has an optional variable gender:

    var gender: Gender?
    

    where Gender is an enum

    enum Gender {
      case Male, Female
    }
    

    you could have convenience initializers like this

    convenience init(maleWithName: String) {
       self.init(name: name)
       gender = .Male
    }
    
    convenience init(femaleWithName: String) {
       self.init(name: name)
       gender = .Female
    }
    

    Convenience initializers must call the designated or required initializers in them. If your class is a subclass, it must call super.init() within it's initialization.

提交回复
热议问题