Vyacheslav Vyacheslav - 1 month ago 14
Swift Question

Variable inside optional variable

I have got something like this:

let index = row.section?.index ?? -1


What is
row.section
is nil?
Please, help me to understand how this line works?

This is easy to understand
locationManager?.startUpdatingLocation()
: method will be executed is
locationManager
is not
nil
. But while assignment optional variable into notnull instance is confusing me.

Answer

From the documentation (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html)

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.

In this case, if row.section is nil, the entire expression (row.section?.index) is nil, therefore index will be set to -1

This line let index = row.section?.index should be incorrect. It must be wrapped into let index = (row.section?.index)!