gpt4 book ai didi

Python "or"在 Swift 中等效?

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:04 25 4
gpt4 key购买 nike

由于 Swift 的酷行为,我正在寻找 Swift 中的 等价物。

像这样:

variable = value or default

我编码了 mine :

func |<T>(a:T?, b:T) -> T {
if let a = a {
return a
}
return b
}

但我想知道 Swift 中是否已经存在任何默认实现?

编辑:感谢答案,我在 Swift 书中找到了引用资料:

Nil Coalescing Operator

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.

The nil coalescing operator is shorthand for the code below:

    a != nil ? a! : b

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 "or"在 Swift 中等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26098920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com