问题
I came across a syntax in Swift where double question marks are used ("??").
For instance, let val = something["something"] as? String ?? nil
What exactly does this mean? What are some use cases for this syntax?
回答1:
Nil-Coalescing Operator
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"
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.
If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.
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"
See section Nil-Coalescing Operator here
回答2:
This operator is generally used to provide a default value when an assigned expression or variable produces an optional result. for ex:
let i: Int? = 5
let j: Int? = nil
let value1 = i ?? 9 //value1 will be 5 non-optional
let value2 = j ?? 9 //value2 will be 9 non-optional
The example you've provided although syntactically correct is redundant, as omitting the ?? nil
would have no result on the outcome.
回答3:
This is Nil-Coalescing Operator
in 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.
But in your example you already using optional binding , so no need of using ??
with optional, if it fails condition then it automatically assign nil
.
let val = something["something"] as? String ?? nil
Here, something["something"] as? String
, already assign nil
, if something["something"]
fails to deliver String
. So no need of this operator here.
来源:https://stackoverflow.com/questions/47362914/what-is-the-meaning-of-in-swift