为Swift中的Optional提供默认值? [英] Providing a default value for an Optional in Swift?

查看:98
本文介绍了为Swift中的Optional提供默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中处理可选选项的习惯用法似乎过于冗长,如果您只想在nil为零的情况下提供默认值,就可以了:

The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it's nil:

if let value = optionalValue {
    // do something with 'value'
} else {
    // do the same thing with your default value
}

涉及不必要的代码重复,或者

which involves needlessly duplicating code, or

var unwrappedValue
if let value = optionalValue {
    unwrappedValue = value
} else {
    unwrappedValue = defaultValue
}

要求unwrappedValue不是常数.

Scala的Option monad(与Swift的Optional的想法基本相同)具有用于此目的的方法getOrElse:

Scala's Option monad (which is basically the same idea as Swift's Optional) has the method getOrElse for this purpose:

val myValue = optionalValue.getOrElse(defaultValue)

我错过了什么吗? Swift已经有一种紧凑的方式来做到这一点吗?否则,是否有可能在Optional扩展名中定义getOrElse?

Am I missing something? Does Swift have a compact way of doing that already? Or, failing that, is it possible to define getOrElse in an extension for Optional?

推荐答案

更新

Apple现在添加了一个合并运算符:

Apple has now added a coalescing operator:

var unwrappedValue = optionalValue ?? defaultValue


在这种情况下,三元运算符是您的朋友


The ternary operator is your friend in this case

var unwrappedValue = optionalValue ? optionalValue! : defaultValue

您还可以为Optional枚举提供自己的扩展名:

You could also provide your own extension for the Optional enum:

extension Optional {
    func or(defaultValue: T) -> T {
        switch(self) {
            case .None:
                return defaultValue
            case .Some(let value):
                return value
        }
    }
}

然后您可以做:

optionalValue.or(defaultValue)

但是,我建议您坚持使用三元运算符,因为其他开发人员将无需研究or方法就可以更快地了解这一点

However, I recommend sticking to the ternary operator as other developers will understand that much more quickly without having to investigate the or method

注意:我启动了模块,以便在or这样的常用帮助器. >快速.

Note: I started a module to add common helpers like this or on Optional to swift.

这篇关于为Swift中的Optional提供默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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