问题描述
由于Swift很酷的行为,我一直在寻找Swift中的or
等效项.
Due to Swift cool behaviors I was looking for an or
equivalent in Swift.
类似这样的东西:
variable = value or default
我编码了我的:
func |<T>(a:T?, b:T) -> T {
if let a = a {
return a
}
return b
}
但是我想知道Swift中是否已经存在任何默认实现?
But I was wondering if any default implementation of this already exists in Swift?
多亏了答案,我在Swift书中找到了参考文献:
Thanks to answers I found the reference in the Swift book:
nil合并运算符(a ?? b
)如果包含一个可选值a,则将其拆开;如果a
为nil,则返回默认值b
.表达式a
始终是可选类型.表达式b
必须与存储在a
内部的类型匹配.
The nil coalescing operator (a ?? b
) unwraps an optional a if it contains a value, or returns a default value b
if a
is nil. The expression a
is always of an optional type. The expression b
must match the type that is stored inside a
.
nil合并运算符是以下代码的简写:
The nil coalescing operator is shorthand for the code below:
a != nil ? a! : b
上面的代码使用三元条件运算符并强制展开(a!
),以在a
不为nil时访问包装在a
中的值,否则返回b
. nil合并运算符提供了一种更简洁的方法,以简洁易读的形式封装此条件检查和展开. (源)
The code above uses the ternary conditional operator and forced unwrapping (a!
) to access the value wrapped inside a
when a
is not nil, and to return b
otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form. (source)
推荐答案
使用??
:
var optional:String?
var defaultValue:String = "VALUE"
var myString:String = optional ?? defaultValue
print(myString)
这篇关于Python“或"等价于Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!