Swift中的多个初始化器

时间:2018-07-03 18:18:37

标签: swift class init

Error: play.playground:34:5: error: invalid redeclaration of 'init'

如何在Swift中为一个类提供多个初始化程序?我以为如果为每个init提供不同的参数,则每个init将具有不同的方法签名,并且可以创建多个参数。为什么这样不起作用,或者我在其他地方犯了错误? (下面是从操场上拉出来的。)

//make a class
class Human{
    var name: String
    var age: Int
    init(_ name: String){
        self.name = name
        self.age = -1
    } 
    init(name: String, age: Int){
        self.name = name
        self.age = age

    }
}

var newHuman = Human("bob")
print(newHuman.name)

var newHuman2 = Human(name: "Marmelade", age: 19)
print(newHuman2)

3 个答案:

答案 0 :(得分:1)

您可以传递更多具有默认值的参数,例如 gender:String =“”

init(name: String, age: Int = 0, gender: String = ""){
    self.name = name
    self.age = age

}

var newHuman = Human("bob")
print(newHuman.name)

var newHuman2 = Human(name: "lol", age: 0)
print(newHuman2)

var newHuman3 = Human(name: "lol", age: 3, gender: "Male")
print(newHuman2)

答案 1 :(得分:0)

您尝试过convenience关键字吗?

//make a class
class Human{
    var name: String
    var age: Int
    convenience init(_ name: String){
        self.init(name: name, age: -1)
    }
    init(name: String, age: Int){
        self.name = name
        self.age = age

    }
}

var newHuman = Human("bob")
print(newHuman.name)

var newHuman2 = Human(name: "Marmelade", age: 19)
print(newHuman2)

答案 2 :(得分:-3)

class Your_ViewController : UIViewController {

    var yourFirstProperty : String?
    var yourSecondProperty : String?

    init(yourFirstProperty: String) {
        self.yourFirstProperty = yourFirstProperty
        self.yourSecondProperty = nil
        super.init(nibName: nil, bundle: nil)
    }

    init(yourSecondProperty: String) {
        self.yourSecondProperty = yourSecondProperty
        self.yourFirstProperty = nil
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) is not supported")
    }
}

您可以轻松地为您的视图控制器使用多个初始化程序,在这里,我编写了一个可以通过两种方式进行初始化的视图控制器,

  

这是针对使用纯代码制作UI的程序员的