考虑 Swift 中的这个类:
class Zombie: Monster {
var walksWithLimp = true
final override func terrorizeTown()
{
town?.changePopulation(-10)
super.terrorizeTown()
}
func changeName(name: String, walksWithLimp: Bool)
{
self.name = name
self.walksWithLimp = walksWithLimp
}
}
Zombie 继承了 Monster 类的 name 字段。
var name = "Monster"
为什么
fredTheZombie.changeName("Tom", walksWithLimp: true)
即使在函数头之前没有 mutating 关键字也能工作吗?
最佳答案
来自 The Language Guide - Methods :
Modifying Value Types from Within Instance 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 ...
因此,我们需要包含关键字 mutating
允许 value 类型的成员(例如函数†)改变其成员(例如 struct
的成员属性)。改变值类型实例的成员意味着改变值类型实例本身(self
),而改变引用类型实例的成员并不意味着引用类型实例的引用(这是被认为是 self
) 发生了突变。
因此,由于 class
是 Swift 中的引用类型,我们不需要包含 mutating
Zombie
的任何实例方法中的关键字类,即使它们改变了实例成员或类。如果我们要谈论改变实际的类实例 fredTheZombie
,我们会指的是改变它的实际引用(例如指向另一个 Zombie
实例)。
[†]:作为另一个例子,我们可以使用例如mutating
setter/getter (get
);在这种情况下,我们需要明确标记为 nonmutating
默认。另一方面,二传手 ( set
) 是 mutating
默认情况下,因此不需要 mutating
关键字,即使它们改变了值类型的成员。
关于swift - 类内的变异函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422781/