duc
(duc)
1
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!
Nevin
2
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
duc
(duc)
3
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?
Nevin
4
That is how optional chaining works, yes. I recommend you read about it in the Swift language guide.
1 Like
duc
(duc)
5
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!!!