我可以在初始化器中使用其他初始化器吗?

class Car {
    var manufacturer:String?
    var speed:Int?

    init (manufacturer manf:String){
        manufacturer = manf
    }

    init(manufacturer manf:String, speed spd:Int){
        manufacturer = manf // How can I use the other initializer here?
        speed = spd

    }
}


var b = Car(manufacturer: "bmw")

var k = Car(manufacturer: "kia", speed: 30)

最佳答案

我想到了。我只需要convenience在我的辅助init之前,然后可以使用self.init调用原始的init

class Car {
    var manufacturer:String?
    var speed:Int?

    init (manufacturer manf:String){
        manufacturer = manf
    }

    convenience init(manufacturer manf:String, speed spd:Int){
        self.init(manufacturer: manf)
        speed = spd

    }
}

关于swift - 在Swift的初始化器中使用其他类初始化器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24195820/

10-09 09:13