Left hand side operand with optional chaining

Hi everyone, I'm trying to understand what happens with this code

var i: Int?
i? += 1
print(i)     // nil

As I understand, i? is Int? and 1 is Int but somehow += operator still works on operands with 2 different types (Int? and Int).
Could anyone help me explain how everything works under the hood?
Thanks!

This is optional chaining, and making this work is the entire purpose of the assignment property in precedencegroup declarations.

It is equivalent to writing something like:

i?.plusEquals(1)
1 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 left is nil?

That is how optional chaining works, yes. I recommend you read about it in the Swift language guide.

1 Like

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) :sweat_smile:.

I will try to read again. Maybe I missed something.
Thank you very much!!!