以下是 Swift 中常用关键字的分类及具体示例,特别补充了 Swift 并发相关内容,帮助理解每个关键字的使用场景:
一、声明修饰符 (Declaration Modifiers)
-
mutating
用途:允许结构体或枚举的方法修改实例属性。struct Counter { var count = 0 mutating func increment() { // 必须声明 mutating count += 1 } }
-
static
用途:定义类型级别的属性或方法(结构体/枚举)。struct MathUtils { static let pi = 3.1415 static func square(_ x: Int) -> Int { x * x } } print(MathUtils.pi) // 直接通过类型访问
-
class
(修饰方法)
用途:定义类方法,子类可重写。class Animal { class func sound() { print("Animal sound") } } class Dog: Animal { override class func sound() { print("Woof!") } // 重写类方法 }
-
final
用途:禁止子类重写或继承。final class MyFinalClass {} // 不可被继承 class MyBaseClass { final func cannotOverride() {} // 不可被重写 }
-
required
用途:强制子类实现指定初始化方法。class Vehicle { required init() {} // 子类必须实现 } class Car: Vehicle { required init() {} // 必须添加 required }
二、访问控制 (Access Control)
-
public
用途:允许跨模块访问。public struct APIClient { // 其他模块可访问 public static let baseURL = "https://api.example.com" }
-
private
用途:仅在当前作用域内访问。class DataManager { private var secretKey = "12345" // 仅在 DataManager 内访问 }
三、类型定义 (Types)
-
class
用途:定义引用类型(支持继承)。class Person { var name: String init(name: String) { self.name = name } }
-
struct
用途:定义值类型(默认不可继承)。struct Point { var x: Int, y: Int }
-
enum
用途:定义枚举类型(关联值、方法)。enum NetworkError: Error { case timeout(duration: Int) case serverError(code: Int) }
-
protocol
用途:定义协议(方法/属性约束)。protocol Drawable { func draw() }
四、函数与闭包参数 (Function/Closure)
-
inout
用途:允许函数修改外部变量。func swapValues(_ a: inout Int, _ b: inout Int) { let temp = a a = b b = temp } var x = 1, y = 2 swapValues(&x, &y) // x=2, y=1
-
@escaping
用途:标记闭包可能在函数返回后执行(如异步操作)。func fetchData(completion: @escaping (Data) -> Void) { DispatchQueue.global().async { let data = Data() completion(data) // 异步回调 } }
-
rethrows
用途:函数本身不抛出错误,但参数闭包可能抛出。func process(_ closure: () throws -> Void) rethrows { try closure() // 仅当闭包抛出错误时,函数才会抛出 }
五、内存管理 (Memory Management)
-
weak
用途:弱引用(自动置为nil
)。class ViewController { weak var delegate: DataDelegate? // 避免循环引用 }
-
unowned
用途:无主引用(假定对象始终存在)。class CreditCard { unowned let owner: Person // owner 必须比 CreditCard 生命周期长 }
六、错误处理 (Error Handling)
-
throws
用途:标记函数可能抛出错误。func readFile(path: String) throws -> String { guard FileManager.default.fileExists(atPath: path) else { throw FileError.notFound } return try String(contentsOfFile: path) }
-
defer
用途:延迟执行代码块(常用于清理资源)。func writeToFile() { let file = openFile() defer { closeFile(file) } // 函数返回前执行 // 写入操作... }
七、模式匹配与泛型 (Patterns & Generics)
-
where
用途:添加类型约束。func findIndex<T: Equatable>(of value: T, in array: [T]) -> Int? { return array.firstIndex(where: { $0 == value }) }
-
associatedtype
用途:协议中定义关联类型。protocol Container { associatedtype Item var items: [Item] { get } }
八、实用工具 (Utilities)
-
lazy
用途:延迟初始化属性。class ImageLoader { lazy var cachedImage: UIImage = { return UIImage(named: "placeholder")! }() }
-
guard
用途:提前退出条件不满足的情况。func processUser(input: String?) { guard let input = input else { return } // 确保 input 非空 // 安全使用 input }
-
@discardableResult
用途:允许忽略函数返回值。@discardableResult func log(message: String) -> Bool { print(message) return true } log(message: "Hello") // 无需接收返回值
九、Swift 并发 (Swift Concurrency)
-
async
/await
用途:定义和调用异步函数。func fetchData() async throws -> Data { let url = URL(string: "https://api.example.com/data")! let (data, _) = try await URLSession.shared.data(from: url) return data }
-
Task
用途:创建并发任务。Task { let data = try await fetchData() // 在后台线程执行 print("Received data: \(data)") }
-
actor
用途:定义 Actor 类型(线程安全的数据隔离)。actor BankAccount { private var balance: Double = 0 func deposit(_ amount: Double) { balance += amount } } let account = BankAccount() Task { await account.deposit(100) // 通过 await 安全访问 }
以下是 Swift 关键字的分类总结表,包含关键字的作用和目的,并补充完善了部分分类和内容,尤其强化了 Swift 并发相关特性:
总结表:Swift 关键字分类、作用及目的
分类 | 关键字 | 作用和目的 |
---|---|---|
声明修饰符 | mutating |
允许结构体/枚举方法修改实例属性(值类型内部可变性)。 |
static |
定义类型级别的属性或方法(结构体/枚举专用)。 | |
class |
定义类方法(可被子类重写)。 | |
final |
禁止继承或重写(用于类或方法/属性)。 | |
required |
强制子类必须实现指定初始化方法。 | |
访问控制 | open |
允许跨模块继承和重写(类的最高访问级别)。 |
public |
允许跨模块访问,但不可继承(默认模块接口)。 | |
internal |
模块内访问(默认级别)。 | |
fileprivate |
同一文件内访问。 | |
private |
当前作用域内访问(最严格)。 | |
类型定义 | class |
定义引用类型(支持继承、引用语义)。 |
struct |
定义值类型(默认不可变、复制语义)。 | |
enum |
定义枚举类型(支持关联值和模式匹配)。 | |
protocol |
定义协议(约束方法、属性或关联类型)。 | |
typealias |
为现有类型定义别名(简化复杂类型名)。 | |
函数/闭包 | inout |
允许函数修改外部变量(通过引用传递参数)。 |
@escaping |
标记闭包可能在函数返回后执行(用于异步或存储闭包)。 | |
rethrows |
函数仅当参数闭包抛出错误时才抛出错误(简化错误传递)。 | |
内存管理 | weak |
弱引用(自动置为 nil ,避免循环引用)。 |
unowned |
无主引用(假定对象始终存在,需手动管理生命周期)。 | |
错误处理 |
throws /throw
|
标记函数可能抛出错误(throws )或主动抛出错误(throw )。 |
try /try? /try!
|
调用可能抛出错误的函数(安全捕获、可选解包或强制解包)。 | |
defer |
延迟执行代码块(确保资源清理或收尾操作)。 | |
模式匹配 | where |
添加类型或条件约束(泛型、switch 、for-in 等)。 |
associatedtype |
在协议中定义关联类型(泛型协议的核心)。 | |
泛型 | some |
定义不透明类型(隐藏具体类型,保留协议约束)。 |
any |
表示存在类型(动态分发,Swift 5.6+ 替代 Protocol 的用法)。 |
|
实用工具 | lazy |
延迟初始化属性(首次访问时计算)。 |
guard |
提前退出条件不满足的情况(确保后续代码安全性)。 | |
@discardableResult |
允许忽略函数返回值(避免未使用结果的警告)。 | |
@available |
标记代码的版本兼容性(指定平台或系统版本)。 | |
Swift 并发 |
async /await
|
定义和调用异步函数(简化异步代码,避免回调地狱)。 |
Task |
创建并发任务(管理异步操作的执行和取消)。 | |
actor |
定义 Actor 类型(线程安全的数据隔离,防止数据竞争)。 | |
@MainActor |
确保代码在主线程执行(UI 更新或主线程敏感操作)。 | |
Sendable |
标记类型可安全跨线程传递(并发安全的类型约束,如值类型、final 类)。 |
关键补充说明
1. Swift 并发
-
async
/await
:
用于编写非阻塞异步代码,替代传统的闭包回调,使代码更线性易读。func fetchImage() async -> UIImage { let data = await downloadData() // 异步等待数据 return UIImage(data: data)! }
-
actor
:
通过隔离数据访问确保线程安全,避免锁机制。actor Counter { private var value = 0 func increment() { value += 1 } func getValue() -> Int { value } }
2. 泛型改进
-
some
(不透明类型):
返回特定协议类型,隐藏具体实现。func makeShape() -> some Shape { // 返回某个具体 Shape 类型 return Circle(radius: 10) }
-
any
(存在类型):
动态分发协议类型(替代旧版Protocol
用法)。var shapes: [any Shape] = [Circle(), Rectangle()]
3. 访问控制
-
open
vspublic
:-
open
:允许其他模块继承和重写(仅限类)。 -
public
:允许其他模块访问,但不可继承。
-
总结
通过分类和明确作用,可以更系统地掌握 Swift 关键字的设计意图:
-
安全性:如
weak
、unowned
管理内存,throws
明确错误处理。 -
表达力:如
async/await
简化异步代码,actor
解决并发问题。 -
灵活性:如
where
添加泛型约束,@escaping
控制闭包生命周期。
此表可作为快速查阅手册,帮助理解 Swift 语言的核心机制和现代特性。