I'm currently learning Swift from basics. Now I'm on optionals and I'm trying to understand this case:
var text: String? = nil
text? = "some text"
What happens exactly if we assign value with question mark? I don't understand why the value of text is nil
. Can you explain me what is the difference between assigning text = "some text"
and text? = "some text"
?
You're right to be surprised. text? =
means "If text
is nil
don't perform the assignment."
You've stumbled across a highly obscure language feature. See https://ericasadun.com/2017/01/25/pretty-much-every-way-to-assign-optionals/ (As she rightly says, you can count on the fingers of zero hands the number of times you'll ever actually talk like this, because who would ever want to assign a value only just in case the lvalue is already non-nil?)
NOTE I prefer to look at this as a zero-length variant of optional chaining. It is extremely useful to be able to say e.g.
self.navigationController?.hidesBarsOnTap = true
meaning, if self.navigationController
is nil
, fuhgeddaboudit. Well, your use case is sort of a variant of that, with nothing after the question mark. Most people are unaware that if the last object in the chain is an Optional, the chain can end in a question mark. The expressions in f
are all legal:
class C {
struct T {
var text : String?
}
var t : T?
func f() {
self.t?.text = "howdy"
self.t? = T()
self.t?.text? = "howdy"
}
}
But only the first one, self.t?.text =
, is common to say in real life.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With