方法 #
一、方法概述 #
方法是与特定类型关联的函数,分为实例方法和类型方法。
1.1 方法类型 #
- 实例方法:实例调用
- 类型方法:类型调用(static/class)
二、实例方法 #
2.1 基本用法 #
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)
print(counter.count)
2.2 self属性 #
swift
struct Point {
var x: Double
var y: Double
func distance(to point: Point) -> Double {
let dx = x - point.x
let dy = y - point.y
return sqrt(dx * dx + dy * dy)
}
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
2.3 修改值类型 #
swift
struct Point {
var x: Double
var y: Double
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var point = Point(x: 0, y: 0)
point.moveBy(x: 10, y: 20)
print("(\(point.x), \(point.y))")
三、类型方法 #
3.1 静态方法 #
swift
struct MathUtility {
static func square(_ x: Double) -> Double {
return x * x
}
static func cube(_ x: Double) -> Double {
return x * x * x
}
}
print(MathUtility.square(5))
print(MathUtility.cube(3))
3.2 类方法 #
swift
class Animal {
class func description() -> String {
return "这是一个动物"
}
static func count() -> Int {
return 0
}
}
class Dog: Animal {
override class func description() -> String {
return "这是一只狗"
}
}
print(Animal.description())
print(Dog.description())
3.3 工厂方法 #
swift
class Product {
var name: String
var price: Double
init(name: String, price: Double) {
self.name = name
self.price = price
}
static func createDefault() -> Product {
return Product(name: "默认产品", price: 0)
}
static func createPremium() -> Product {
return Product(name: "高级产品", price: 100)
}
}
let defaultProduct = Product.createDefault()
let premiumProduct = Product.createPremium()
四、下标 #
4.1 基本语法 #
swift
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let timesTable = TimesTable(multiplier: 3)
print(timesTable[5])
4.2 可写下标 #
swift
struct Matrix {
var rows: Int
var columns: Int
private var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0, count: rows * columns)
}
subscript(row: Int, column: Int) -> Double {
get {
return grid[row * columns + column]
}
set {
grid[row * columns + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 0] = 1.0
matrix[0, 1] = 2.0
matrix[1, 0] = 3.0
matrix[1, 1] = 4.0
print(matrix[0, 0])
print(matrix[1, 1])
4.3 类型下标 #
swift
enum Direction: Int {
case north = 0
case south
case east
case west
static subscript(direction: String) -> Direction? {
switch direction.lowercased() {
case "north": return .north
case "south": return .south
case "east": return .east
case "west": return .west
default: return nil
}
}
}
if let direction = Direction["north"] {
print(direction)
}
五、方法参数 #
5.1 默认参数值 #
swift
class Calculator {
func add(_ a: Int, _ b: Int = 0) -> Int {
return a + b
}
func multiply(_ a: Int, by b: Int = 1) -> Int {
return a * b
}
}
let calc = Calculator()
print(calc.add(5))
print(calc.add(5, 3))
5.2 可变参数 #
swift
class Math {
func sum(_ numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
func average(_ numbers: Double...) -> Double {
guard !numbers.isEmpty else { return 0 }
return numbers.reduce(0, +) / Double(numbers.count)
}
}
let math = Math()
print(math.sum(1, 2, 3, 4, 5))
print(math.average(1.0, 2.0, 3.0, 4.0, 5.0))
5.3 输入输出参数 #
swift
func swap(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 1
var y = 2
swap(&x, &y)
print("x: \(x), y: \(y)")
六、实际应用 #
6.1 链式调用 #
swift
class Builder {
private var name: String = ""
private var age: Int = 0
func setName(_ name: String) -> Builder {
self.name = name
return self
}
func setAge(_ age: Int) -> Builder {
self.age = age
return self
}
func build() -> String {
return "\(name), \(age)岁"
}
}
let result = Builder()
.setName("张三")
.setAge(25)
.build()
print(result)
6.2 策略模式 #
swift
protocol SortStrategy {
func sort(_ numbers: [Int]) -> [Int]
}
class AscendingSort: SortStrategy {
func sort(_ numbers: [Int]) -> [Int] {
return numbers.sorted { $0 < $1 }
}
}
class DescendingSort: SortStrategy {
func sort(_ numbers: [Int]) -> [Int] {
return numbers.sorted { $0 > $1 }
}
}
class Sorter {
private var strategy: SortStrategy
init(strategy: SortStrategy) {
self.strategy = strategy
}
func setStrategy(_ strategy: SortStrategy) {
self.strategy = strategy
}
func sort(_ numbers: [Int]) -> [Int] {
return strategy.sort(numbers)
}
}
6.3 命令模式 #
swift
protocol Command {
func execute()
func undo()
}
class Light {
func on() { print("灯开了") }
func off() { print("灯关了") }
}
class LightOnCommand: Command {
private let light: Light
init(light: Light) {
self.light = light
}
func execute() { light.on() }
func undo() { light.off() }
}
class LightOffCommand: Command {
private let light: Light
init(light: Light) {
self.light = light
}
func execute() { light.off() }
func undo() { light.on() }
}
class RemoteControl {
private var command: Command?
func setCommand(_ command: Command) {
self.command = command
}
func pressButton() {
command?.execute()
}
func pressUndo() {
command?.undo()
}
}
七、总结 #
本章学习了Swift方法:
- 实例方法:实例调用
- 类型方法:类型调用
- 下标:访问语法
- mutating:修改值类型
最佳实践:
- 使用描述性方法名
- 合理使用默认参数
- 使用下标简化访问
- 链式调用提高可读性
下一章,我们将学习继承!
最后更新:2026-03-26