Hi everyone, I'm trying to understand what happens with this code
var i: Int?
i? += 1
print(i) // nil
As I understand,
Int but somehow
+= operator still works on operands with 2 different types (
Could anyone help me explain how everything works under the hood?
This is optional chaining, and making this work is the entire purpose of the
assignment property in
It is equivalent to writing something like:
Yes, I also guessed that it will be equivalent to
i?.plusEquals(1). But in this case,
i = 1 will be
i.plusEquals(1). It makes me quite confused.
Btw, I know
i? += 1 will call
static func += (left: inout Int, right: Int) function. Does Swift automatically evaluate
left parameter and skip the function if
That is how optional chaining works, yes. I recommend you read about it in the Swift language guide.
Actually I read Basic Operators, Optional Chaining, Advanced Operators.
I know when I call a function on an optional variable, the variable will be evaluated before function is called. But I can't find any section which mentions about evaluating parameters before calling static function (operators) .
I will try to read again. Maybe I missed something.
Thank you very much!!!