一、什么是 Swift 方法
方法是与特定类型(类、结构体、枚举)关联的函数。Swift 中的方法分为两类:实例方法 和类型方法。与 C 或 Objective-C 不同,Swift 的结构体和枚举也能定义方法,这是 Swift 面向协议与值语义设计的重要基础。
方法的核心价值在于:把与数据相关的行为封装在类型内部,让调用方通过对象或类型直接访问,提升代码的可读性与内聚性。
二、实例方法
实例方法属于某个具体的实例,需要通过实例调用。它可以直接访问该实例的属性和其他方法。
swift
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
counter.increment(by: 5)
counter.reset()
上面的 increment() 与 increment(by:) 构成了方法重载:方法名相同但参数列表不同,Swift 会依据参数标签和类型选择正确的实现。
2.1 self 属性
每个实例方法内部都隐含一个名为 self 的属性,指向当前实例。大多数情况下无需显式书写,但当参数名与属性名冲突时,可以用 self 加以区分。
swift
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOf(x: Double) -> Bool {
return self.x > x
}
}
这里的 self.x 表示实例属性,而参数 x 是局部变量,二者不会混淆。
2.2 在实例方法中修改值类型
结构体和枚举是值类型,默认情况下其属性不能在实例方法中被修改。若需要修改,必须给方法加上 mutating 关键字。
swift
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// 输出:The point is now at (3.0, 4.0)
注意:
mutating方法只能被变量实例调用。若用let声明常量实例,则无法调用 mutating 方法,因为常量实例的属性不可变。
2.3 mutating 方法中给 self 赋值
mutating 方法除了修改属性,还可以直接给 self 赋一个全新的实例,从而整体替换当前值。
swift
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
对于枚举,mutating 方法还可以把 self 设置为另一个枚举成员:
swift
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() // .high
ovenLight.next() // .off
三、类型方法
类型方法定义在类型本身上,而不是某个实例上。使用 static 或 class 关键字声明:
static func:定义静态方法,不能被子类重写。class func:仅用于类,允许子类重写。
swift
struct MathHelper {
static func square(_ value: Double) -> Double {
return value * value
}
}
print(MathHelper.square(4)) // 16
在类型方法内部,self 指向类型本身而非实例,因此可以直接调用其他类型方法或访问类型属性。
swift
class SomeClass {
class func someTypeMethod() {
// 这里的 self 指向 SomeClass 类型
}
}
SomeClass.someTypeMethod()
四、方法与其他特性的配合
4.1 方法的外部参数名
Swift 方法的第一个参数默认不显示外部标签,从第二个参数开始默认使用参数名作为外部标签。这与普通函数不同,目的是让方法调用读起来更自然。
swift
class Calculator {
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiply(_ a: Int, by b: Int) -> Int {
return a * b
}
}
let calc = Calculator()
calc.add(1, 2)
calc.multiply(3, by: 4)
4.2 方法作为闭包传递
实例方法可以被当作闭包使用,此时方法会捕获对应的实例。
swift
class Greeter {
let name: String
init(name: String) { self.name = name }
func greet() {
print("Hello, \(name)")
}
}
let greeter = Greeter(name: "Swift")
let action: () -> Void = greeter.greet
action() // Hello, Swift
4.3 协议中的方法要求
协议可以声明方法要求,遵循协议的类型必须实现这些方法。若协议方法需要修改遵循者的属性,则需标记为 mutating。
swift
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case off, on
mutating func toggle() {
switch self {
case .off:
self = .on
case .on:
self = .off
}
}
}
五、常见注意事项
| 场景 | 说明 |
|---|---|
| 值类型修改属性 | 必须使用 mutating 方法 |
| 常量实例调用 mutating | 编译报错,需改为 var |
| 类方法重写 | 使用 class func 而非 static func |
| 方法重载 | 依据参数标签与类型区分,返回值不参与重载 |
| 方法引用 | 作为闭包时会强引用实例,注意循环引用 |
六、总结
Swift 方法体系围绕值语义与类型安全展开:实例方法负责操作具体实例,mutating 让值类型也能安全地修改自身状态,类型方法则提供与类型绑定的工具能力。理解 self 的指向、static 与 class 的区别,以及方法在协议与闭包中的表现,是写出地道 Swift 代码的关键。