【问题标题】:Is it possible to write mutating function in swift class?是否可以在 swift 类中编写变异函数?
【发布时间】:2020-02-13 12:35:55
【问题描述】:
我可以在结构中编写变异函数,但不能在类中编写。
struct Stack {
public private(set) var items = [Int]() // Empty items array
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int? {
if !items.isEmpty {
return items.removeLast()
}
return nil
}
}
【问题讨论】:
标签:
swift
mutating-function
【解决方案1】:
在 Swift 中,类是引用类型,而结构和枚举是值类型。默认情况下,值类型的属性不能在其实例方法中修改。为了修改值类型的属性,您必须在实例方法中使用 mutating 关键字。使用此关键字,您的方法就可以在方法实现结束时改变属性值并将其写回原始结构。
【解决方案2】:
如果将结构更改为类,只需删除关键字mutating 出现的任何位置。
【解决方案3】:
这是因为类是引用类型,结构是值类型。
struct TestValue {
var a : Int = 42
mutating func change() { a = 1975 }
}
let val = TestValue()
val.a = 1710 // Forbidden because `val` is a `let` of a value type, so you can't mutate it
val.change() // Also forbidden for the same reason
class TestRef {
var a : Int = 42
func change() { a = 1975 }
}
let ref = TestRef()
ref.a = 1710 // Allowed because `ref` is a reference type, even if it's a `let`
ref.change() // Also allowed for the same reason
所以在类上,你不需要指定函数是否发生变异,因为即使使用let 变量定义,你也可以修改实例...
这就是为什么mutating 关键字在类中没有意义。