Implicitly unwrapped optional made immutable

后端 未结 2 589
盖世英雄少女心
盖世英雄少女心 2020-12-06 11:22

Why is it that I cannot mutate an implicitly unwrapped optional variable?

Here is a short example the reproduces the issue:

With Array

var          


        
2条回答
  •  天涯浪人
    2020-12-06 12:15

    Because the way you are trying to mutate them is by mutating the values (which are immutable) instead of mutating the var.

    In Swift value types are immutable. All and always.

    Mutation is not a mutation of the value, it's a mutation of the variable that contains the value.

    In the case of the Int, the += operator gets a structure on the left and an Int on the right, and it cannot add a structure to an int.

    In the case of the Array the append is a mutating member. But it's being invoked on an immutable value that is not directly stored in a variable. It can only operate on values that are directly stored in a variable (which is what makes them mutable: the fact that they are stored in a variable. They are not really mutable, the variable is).

提交回复
热议问题