Fogmeister Fogmeister - 1 year ago 79
Swift Question

Swift ?? on a type

I know what the ?? is when used as an operator but what does it mean when it is on a Type?

I have a struct in my project called

and the autocompletion of a particular var tells me it is of type

Not really sure what that means or how to unwrap it safely.

Answer Source

As others have said, it's a double Optional, completely unrelated to the nil coalescence operator (??).

To unwrap it, you just unwrap a regular optional, twice:

let doubleOptional: MyStruct?? = MyStruct()

guard let singleOptional = doubleOptional else {
    //first unwrapping failed

guard let wrappedValue = singleOptional else {
    //second unwrapping failed

//use wrappedValue

These are quite uncommon, but there are times when they're useful.

For example, consider you have a data structure that stores an average of an array. The array might be empty, thus the average should be allowed to be nil, to indicate there is no average. Suppose calculating this average is very expensive and we want to store it in a caching layer. This caching layer could have a double optional representing that average. If the value is Optional.None (i.e. nil), we know the cache doesn't have a value yet, thus it needs to be computed. If the value is Optional.Some(Optional.None), we know the cache has a value, but that there is no valid average (i.e. the array was empty. Lastly, the value could be Optional.Some(Optional.Some(/*...*/)), which represents a valid cache value of a valid average.