加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 类内的变异函数

发布时间:2020-12-14 04:53:35 所属栏目:百科 来源:网络整理
导读:在 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.wal
在 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)默认是变异的,因此即使它们改变了值类型的成员也不需要变异关键字.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读