传入值的函数参数的默认值为nil

时间:2014-11-28 14:41:48

标签: swift default-parameters optional-values

是否有一种简洁的方法来组合默认函数参数值和选项,因此当在函数调用中指定参数时,参数将采用提供的默认值,但它的值是否为nil?

例如:

class MyObj {

    var foobar:String

    init(foo: String?="hello") {
        self.foobar = foo!
    }
}

let myObj = MyObj() // standard use of default values - don't supply a value at all

println(myObj.foobar) // prints "hello" as expected when parameter value is not supplied

var jimbob: String? // defaults to nil

...

// supply a value, but it is nil
let myObj2 = MyObj(foo: jimbob) // <<< this crashes with EXC_BAD_INSTRUCTION due to forced unwrap of nil value

println(myObj2.foobar)

...或者是给成员常量/变量默认值的最佳选择,然后只有在为构造函数提供值时才更改它们,如下所示:

let foobar:String = "hello"

init(foo: String?) {
    if foo != nil {
       self.foobar = foo!
    }
}

考虑到该领域的其他语言特征,应该有一个更整洁的解决方案。

1 个答案:

答案 0 :(得分:15)

怎么样:

class MyObj {

    var foobar:String

    init(foo: String?=nil) {
        self.foobar = foo ?? "hello"
    }
}
相关问题