What does this question mark mean?

I came across this code and I couldn't figure out what these two question marks mean?

The definition of this variable looks like this:

var featureImageSizeOptional: CGSize?   

      

The code that confuses me:

let featureImageSize = featureImageSizeOptional ?? CGSizeZero

      

+3


source to share


2 answers


This is a coalescing operator. It returns the first expression ( featureImageSizeOptional

) if it is nonzero. If the first expression is nil, the operator returns the second expression ( CGSizeZero

).



See the Language Guide for details .

+10


source


The operator does not return the first expression โ€” it returns the expanded value of the first expression (unless it is nil). From Apple documentation (main focus):



The nil concatenation operator (a? B) unpacks an optional a if it contains a value, or returns the default b if a is nil. the expression a always has an optional type. The b expression must match the type that is stored internally.

The coalescing operator nil is shorthand for the code below:

a! = nil? a! : b

The above code uses the ternary conditional operator and * forced unwrapping (a!) To access the value wrapped inside a when there is no nil * and return b otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional validation and deployment in a concise and readable form.

+3


source







All Articles