微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)认是变异的,因此即使它们改变了值类型的成员也不需要变异关键字.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐