是否可以在 swift class 中编写变异函数?
Is it possible to write mutating function in swift class?
我可以在结构中编写可变函数,但不能在 class 中编写。
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 关键字。有了这个关键字,你的方法就可以改变属性的值,并在方法实现结束时将其写回原始结构。
如果将结构更改为 class,只需删除出现的关键字 mutating
。
那是因为类是引用类型,而结构是值类型。
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
关键字在 类 上没有意义的原因。
我可以在结构中编写可变函数,但不能在 class 中编写。
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 关键字。有了这个关键字,你的方法就可以改变属性的值,并在方法实现结束时将其写回原始结构。
如果将结构更改为 class,只需删除出现的关键字 mutating
。
那是因为类是引用类型,而结构是值类型。
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
关键字在 类 上没有意义的原因。