swift – 类内的变异函数

swift – 类内的变异函数,第1张

概述在 Swift中考虑这个类: class Zombie: Monster { var walksWithLimp = true final override func terrorizeTown() { town?.changePopulation(-10) super.terrorizeTown() } func cha 在 Swift中考虑这个类:

class ZombIE: Monster {    var walksWithlimp = true    final overrIDe func terrorizetown()    {        town?.changePopulation(-10)        super.terrorizetown()    }    func change@R_502_6889@(@R_502_6889@: String,walksWithlimp: Bool)    {        self.@R_502_6889@ = @R_502_6889@        self.walksWithlimp = walksWithlimp    }}

ZombIE继承了Monster类的名字字段.

var @R_502_6889@ = "Monster"

为什么

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

总结

以上是内存溢出为你收集整理的swift – 类内的变异函数全部内容,希望文章能够帮你解决swift – 类内的变异函数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1014319.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存