方法
枚举、结构体、类都可以定义实例方法、类型方法。
- 实例方法(Instance Method): 通过实例对象调用。
- 类型方法(Type Method):通过类型调用,用
static或者class关键词定义。
self
- 在实例方法中,
self代表的是当前实例。 - 在类型方法中,
self代表的是当前类型。
// 方法
class Car {
static var count = 0
init() {
Car.count += 1
}
static func getCount() -> Int {
count // 可以访问的
}
}
let c0 = Car();
let c1 = Car();
print(Car.getCount())
类型方法 static func getCount 中, count等价于self.count、 Car.self.count、Car.count
mutating
结构体和枚举都是值类型,默认情况下,值类型的成员不能被自身的实例方法所修改。
- 在func 关键字前加
mutating可以允许这个修改行为。
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
}
}
enum StateSwitch {
case low, middel, high
mutating func next() {
switch self {
case .low:
self = .middel
case .middel:
self = .high
case .high:
self = .low
}
}
}
@discardableResult
在func 前面加个@discardableResult, 可消除: 函数调用后返回值未被使用的警告。
struct Point {
var x = 0.0, y = 0.0
@discardableResult mutating func moveBy(deltaX: Double, deltaY: Double) -> Int {
x += deltaX
y += deltaY
return 10
}
}
var p = Point()
p.moveBy(deltaX: 1, deltaY: 10)