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

标签 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!
    }
}

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

最佳答案

怎么样:

class MyObj {

    var foobar:String

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

关于swift - 传入值为 nil 的函数参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27191020/

相关文章:

ios - 如何通过在 Spritekit 中触摸隐藏的 SKSpriteNode 来检测它们?

ios - 在 UserDefaults 中保存 UISwitch 状态

javascript - ES6 默认参数 : values not assigned properly

kotlin - 扩展父参数的类默认值

swift - 为什么这样做有效(不使用与使用可选值)?

ios - 展开可选值时发现 nil

swift - 使用 vapor-fluent 更新模型

带不完整参数的 C++ 函数调用

swift - swift 中可选值之间的区别?

swift - 如何使用 UIActivityViewController 将 UIImage 分享到相机胶卷