Cannot assign to 'X' in 'Y' in Swift

后端 未结 3 662
-上瘾入骨i
-上瘾入骨i 2021-02-05 07:04

I have a dictionary with Structs in it. I am trying to assign the values of the struct when I loop through the dictionary. Swift is tellin

3条回答
  •  滥情空心
    2021-02-05 07:43

    Your guess is true.

    By accessing blockStatus, you are creating a copy of it, in this case, it's a constant copy (iterators are always constant).

    This is similar to the following:

    var numbers = [1, 2, 3]
    
    for i in numbers {
       i = 10  //cannot assign here
    }
    

    References:

    Control Flow

    In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop.

    Classes and Structures

    A value type is a type that is copied when it is assigned to a variable or constant, or when it is passed to a function. [...] All structures and enumerations are value types in Swift

    Methods

    Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

    However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

    You can opt in to this behavior by placing the mutating keyword before the func keyword for that method:

提交回复
热议问题