swift - 类内的变异函数

标签 swift function class

考虑 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 类的 name 字段。

var name = "Monster"

为什么

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

即使在函数头之前没有 mutating 关键字也能工作吗?

最佳答案

来自 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允许 value 类型的成员(例如函数)改变其成员(例如 struct 的成员属性)。改变值类型实例的成员意味着改变值类型实例本身(self),而改变引用类型实例的成员并不意味着引用类型实例的引用(这是被认为是 self ) 发生了突变。

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

[†]:作为另一个例子,我们可以使用例如mutating setter/getter (get);在这种情况下,我们需要明确标记为 nonmutating默认。另一方面,二传手 ( set ) 是 mutating默认情况下,因此不需要 mutating关键字,即使它们改变了值类型的成员。

关于swift - 类内的变异函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422781/

相关文章:

swift - Swift 中财务变量的正确数字类型是什么?

ios - ObjC <-> Swift 桥接和工厂方法

C++ 无法专门化函数模板

java - 如何查找并修复 Java 嵌套类中的内存泄漏?

java - 我应该创建一个新变量还是始终访问类对象中的数据?

swift - 在 View 中定位 View

ios - 已收到 KVO 消息但未处理问题 - SWIFT

c++ - 我想在主程序的函数中使用变量集,但是在声明变量时出错

r - 检查某个函数是否在 R 的嵌套函数中使用

C++ 线程 1 : EXC_BAD_ACCESS(code=1, 地址 =0x8