What is the difference between convenience init vs init in swift, explicit examples better

后端 未结 10 1964
醉梦人生
醉梦人生 2021-01-30 08:18

I am having troubles to understand the difference between both, or the purpose of the convenience init.

10条回答
  •  梦谈多话
    2021-01-30 08:52

    Here is a simply example, taken from the Apple Developer portal.

    Basicly the designated initializer is the init(name: String), it ensure that all stored properties are initialized.

    The init() convenience initializer, taking no argument, automaticly sets the value of name stored property to [Unnamed] by using the designated initializer.

    class Food {
        let name: String
    
        // MARK: - designated initializer
        init(name: String) {
            self.name = name
        }
    
        // MARK: - convenience initializer
        convenience init() {
            self.init(name: "[Unnamed]")
        }
    }
    
    // MARK: - Examples
    let food = Food(name: "Cheese") // name will be "Cheese"
    let food = Food()               // name will be "[Unnamed]"
    

    It is usefull, when you are dealing with large classes, with at least a few stored properties. I would recommend to read some more about optionals and inheritance at the Apple Developer portal.

提交回复
热议问题