Swift如何有多个init() [英] How have multiple init() with Swift

查看:195
本文介绍了Swift如何有多个init()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的Class中,是否可以在没有参数的情况下具有多个init(字符串只是一个示例):

Is it possible, if yes how, to have multiple init without parameter, in a Class like this (the string is just an exemple):

aVar: String

init() {
   aVar = "simple init"
}

initWithAGoodVar() {
   aVar = "Good Var!"
}

initWithFooBar() {
   aVar = "Foo Bar"
}

推荐答案

如果没有参数,则不能有多个init,因为要使用哪个init方法是模棱两可的.另外,您也可以将初始值传递给init方法.以您的问题为例:

You cannot have multiple inits without parameters since it would be ambiguous which init method you wanted to use. As an alternative you could either pass the initial values to the init method. Taking the example from your question:

class MyClass {
    var myString: String

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

let a = MyClass(myString: "simple init")

或者,如果仅将myString设置为某些值,则可以使用enum:

Or, if myString is only supposed to be certain values, you could use an enum:

class MyOtherClass {
    enum MyEnum: String {
        case Simple  = "Simple"
        case GoodVar = "GoodVar"
        case FooBar  = "FooBar"
    }

    var myString: String

    init(arg: MyEnum) {
        myString = arg.rawValue
    }
}

let b = MyOtherClass(arg: .GoodVar)
println(b.myString) // "GoodVar"

这篇关于Swift如何有多个init()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆