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.
然而,如果你需要在一个方法内部修改一个结构体或者枚举的属性。你可以选择mutating那个方法的行为。这个方法然后就可以变异在方法内部修改属性值。当方法结束的时候,任何的变化都会返回到原始结构里边。这个方法也可以利用他的隐式self属性赋值给一个新值。
分析
因为你已经申明了结构体实例是常量,因此他的素偶偶属性都不能进行更改了。
swift结构体的mutating
最新推荐文章于 2021-09-14 11:07:55 发布