swift – 类内的变异函数

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类的名字字段.

var name = "Monster"

为什么

fredTheZombie.changeName("Tom",walksWithLimp: true)

即使函数头之前没有变异关键字也可以工作?

解决方法

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以允许值类型的成员(例如函数†)改变其成员(例如结构的成员属性).变换值类型实例的成员意味着改变值类型实例本身(self),而改变引用类型实例的成员并不意味着引用类型实例(被认为是self)的引用被改变.

因此,由于类是Swift中的引用类型,我们不需要在Zombie类的任何实例方法中包含mutating关键字,即使它们改变了实例成员或类.如果我们要谈论改变实际的类实例fredTheZombie,我们会提到改变它的实际引用(例如指向另一个Zombie实例).

[†]:作为另一个例子,我们可以使用例如变异的getters(get);在这种情况下,我们需要明确标记,因为认情况下这些是非突变的.另一方面,Setters(set)认是变异的,因此即使它们改变了值类型的成员也不需要变异关键字.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...