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类的名字字段.
var name = "Monster"
为什么
fredTheZombie.changeName("Tom",walksWithLimp: true)
即使函数头之前没有变异关键字也可以工作?
解决方法
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 implicitself
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以允许值类型的成员(例如函数†)改变其成员(例如结构的成员属性).变换值类型实例的成员意味着改变值类型实例本身(self),而改变引用类型实例的成员并不意味着引用类型实例(被认为是self)的引用被改变.
因此,由于类是Swift中的引用类型,我们不需要在Zombie类的任何实例方法中包含mutating关键字,即使它们改变了实例成员或类.如果我们要谈论改变实际的类实例fredTheZombie,我们会提到改变它的实际引用(例如指向另一个Zombie实例).
[†]:作为另一个例子,我们可以使用例如变异的getters(get);在这种情况下,我们需要明确标记,因为默认情况下这些是非突变的.另一方面,Setters(set)默认是变异的,因此即使它们改变了值类型的成员也不需要变异关键字.