Capturing a struct reference in a closure doesn't allow mutations to occur

后端 未结 3 944
有刺的猬
有刺的猬 2021-01-14 11:14

I am trying to see if I can use structs for my model and was trying this. When I call vm.testClosure(), it does not change the value of x and I am

3条回答
  •  孤街浪徒
    2021-01-14 11:52

    Here is what Apple says about that.

    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 behaviour 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.

    Taken from here

提交回复
热议问题