2016-10-20 3 views
1

Ich habe so etwas wie dieses bekam:Variable innerhalb optionale Variable

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

Was ist row.section Null ist? Bitte helfen Sie mir zu verstehen, wie diese Linie funktioniert?

Dies ist leicht zu verstehen locationManager?.startUpdatingLocation(): Methode wird ausgeführt wird locationManager ist nicht nil. Aber während die Zuweisung der optionalen Variablen in die nonnull-Instanz mich verwirrte.

+1

gewickelt werden, bedeutet dies, dass, wenn row.section? .index ist Null, Index wird gleich -1 – koropok

+0

Was ist 'row.section' ist nil? – Vyacheslav

Antwort

2

Aus der Dokumentation (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html)

Der Null-Koaleszenz-Operator (a ?? b) auspackt optional ein, wenn es einen Wert enthält, oder gibt eine b Standardwert, wenn eine Null ist. Der Ausdruck a ist immer ein optionaler Typ. Der Ausdruck b muss mit dem Typ übereinstimmen, der in a gespeichert ist.

In diesem Fall, wenn row.section Null ist, der gesamte Ausdruck (row.section? .index) gleich Null ist, wird daher Index gesetzt wird -1

Diese Zeile let index = row.section?.index falsch sein sollte. Es muss in let index = (row.section?.index)!

+0

aktualisiert Ihre Antwort ein wenig – Vyacheslav