第十一章 方法
2017-07-16 本文已影响0人
运柱
与c++类似,也是有实例方法和类型方法。
对于结构体、枚举,由于它们是值类型,因此不能在实例方法中修改属性值。
实际应用场景中,又需要修改属性,因此swift提供了mutating方法
struct Point {
var x = 0.0, y = 0.0
mutating func moving(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
}
}
enum Orientation {
case North
case South
case West
case East
mutating func change() {
switch self {
case .East:
self = .South
case .South:
self = .West
case .West:
self = .North
case .North:
self = .East
}
}
}
类型方法
用static关键字来声明类型方法,与类型属性一样。