且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“??"是什么意思?在迅速?

更新时间:2023-11-08 14:59:04

Nil-Coalescing Operator

这是一种简短的形式.(意味着您可以分配默认值 nil 或任何其他值,如果 something["something"]nil 或可选)

It's kind of a short form of this. (Means you can assign default value nil or any other value if something["something"] is nil or optional)

let val = (something["something"] as? String) != nil ? (something["something"] as! String) : "default value"

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-coalescing 运算符是以下代码的简写:

The nil-coalescing operator is shorthand for the code below:

a != nil ?一种!:乙上面的代码使用三元条件运算符和强制解包 (a!) 在 a 不为 nil 时访问包装在 a 中的值,否则返回 b.nil 合并运算符提供了一种更优雅的方式,以简洁易读的形式封装这种条件检查和展开.

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.

如果 a 的值非 nil,则不计算 b 的值.这称为短路评估.

If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

以下示例使用 nil-coalescing 运算符在默认颜色名称和可选的用户定义颜色名称之间进行选择:

The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

请参阅此处的无合并运算符部分