- 枚举、结构体、类都可以定义实例方法(Instance Method)、类型方法(Type Method)
1.实例方法通过实例调用
2.类型方法通过类型调用,用static或者class关键字定义
class Car {
static var count = 0
init() {
Car.count += 1
}
static func getCount() -> Int {
return count
}
}
let c1 = Car()
let c2 = Car()
let c3 = Car()
print(Car.getCount()) // 3
self
self在实例方法中代表实例,在类型方法中代表类型。在类型方法static func getCount()中,cout等价于self.cout、Car.self.cout、Car.cout
mutating
结构体和枚举是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改。
要使用可变方法,将关键字 mutating 放到方法的 func 关键字的前面。
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
//等价
//self = Point(x: 10.5, y: 20.0)
}
}
enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}
var ovenLight = TriStateSwitch.low
ovenLight.next()
// ovenLight 现在等于 .high
ovenLight.next()
// ovenLight 现在等于 .off
@discardableResult
在func前面加个@discardableResult修饰符,可以消除函数调用后返回值未使用的警告⚠️
struct Pointing {
var x = 0.0, y = 0.0
@discardableResult mutating func moveX(deltaX: Double) -> Double {
x += deltaX
return x
}
}
var p = Pointing()
p.moveX(deltaX: 10)
将方法赋值给var、let
struct Person {
var age: Int
func run(_ v: Int) {
print("func run ",age,v)
}
static func run(_ v: Int) {
print("func run ",v)
}
}
方法也可以想函数那样赋值给var、let
- 常规写法:
let p = Person(age: 10)
print(p.age)
p.run(20)
- 赋值给var、let
var fn = Person.run
var fn2 = fn(Person(age: 10))
fn2(20)
类方法和实例方法同时存在时:
- 常规写法:默认调用类方法
let fn = Person.run
fn(20)
- 调用实例方法,要写明类型
let fn: (Person) -> (Int) -> () = Person.run
fn(Person(age: 10))(20)






网友评论