Vyacheslav Vyacheslav - 7 months ago 83
Swift Question

Variable inside optional variable

I have got something like this:

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

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

This is easy to understand
: method will be executed is
is not
. But while assignment optional variable into notnull instance is confusing me.


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)!