Swift : Nil Collision Operator ,Save Your iPhone app from random crashes.

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.

NOTE

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  name and an optional user-defined  name:

let defaultName = “Kandhal”
var userDefinedName: String? // defaults to nil

var NameToUse = userDefinedName ?? defaultName
// userDefinedName is nil, so NameToUse is set to the default of “Kandhal”
The userDefinedName variable is defined as an optional String, with a default value of nil. Because userDefinedName is of an optional type, you can use the nil-coalescing operator to consider its value. In the example above, the operator is used to determine an initial value for a String variable called NameToUse. Because userDefinedName is nil, the expression userDefinedName ?? defaultName returns the value of defaultName, or “red”.

If you assign a non-nil value to userDefinedName and perform the nil-coalescing operator check again, the value wrapped inside userDefinedName is used instead of the default:

userDefinedName = “Kano”
NameToUse = userDefinedName ?? defaultName
// userDefinedName is not nil, so NameToUse is set to “Kano”

Thanks & Best Regards.

 

 

 

You may also like

Leave a Reply