Swift 6.2 内置于 Xcode 26,主要带来了如下的新特性。
标识符
显著扩展了创建标识符的字符范围,当使用``时,可以更随性。
swift
func `this is a function`(param: String) -> String {
return "Hello, \(param)"
}
enum HTTPStatus: String {
case `200` = "Success"
case `404` = "Not Found"
case `500` = "Internal Server Error"
}
字符串插值支持默认值
字符串插值,可以设置默认值。当插值为可选型并且其值为nil
时,可以使用提供的默认值。
swift
var name: String? = nil
// Swift6.2之前
print("Hello, \(name ?? "zhangsan")!")
// Swift6.2之后
print("Hello, \(name, default: "zhangsan")!")
InlineArray
引入了一种新的数组类型,表示固定大小的数组,性能优越。
swift
var array: InlineArray<3, String> = ["zhangsan", "lisi", "wangwu"]
var array2: InlineArray = ["zhangsan", "lisi", "wangwu"]
enumerated()返回的类型遵守Collection
进一步简化了在 SwiftUI 中的使用。
swift
import SwiftUI
struct ContentView: View {
@State private var names = ["ZhangSan", "LiSi", "WangWu"]
var body: some View {
// Swift6.2之前
List(Array(names.enumerated()), id: \.element) { turple in
HStack {
Text("\(turple.offset)")
Text(turple.element)
}
}
// Swift6.2之后
List(names.enumerated(), id: \.element) { turple in
HStack {
Text("\(turple.offset)")
Text(turple.element)
}
}
}
}
weak let
- 引入了
weak let
,允许声明不可变的弱引用属性。 - 解决 Sendable 类型中弱引用的问题。
swift
import UIKit
class ViewController: UIViewController {
// Swift6.2之前
@IBOutlet weak var redView: UIView!
// Swift6.2之后
@IBOutlet weak let greenView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
Backtrace
引入了一个新的结构体,提供运行时堆栈追踪,可以捕获从当前代码处到调用处的函数调用序列。
swift
import Runtime
func functionOne() {
do {
if let frames = try? Backtrace.capture().symbolicated()?.frames {
print(frames)
}
else {
print("Failed to capture backtrace.")
}
} catch {
print(error.localizedDescription)
}
}
func functionTwo() {
functionOne()
}
func functionThree() {
functionTwo()
}
functionThree()
并发编程
- 在 Swift 6.2 之前,nonisolated 异步函数会自动在后台线程执行。但在 Swift 6.2 之后,nonisolated 异步函数将会在调用者的 actor 上执行。此时通过
@concurrent
进行修饰,可以继续让其按照之前的方式运行。 - 当使用
@concurrent
时,函数会发生以下行为。- 将在后台线程运行,即使从主线程调用。
- 创建一个新的隔离,与调用者分离。
- 所有参数和返回值必须符合 Sendable 协议。
- 适用场景。
- 函数执行时间较长。
- 函数是 CPU 密集型或者可能阻塞线程,比如大量的数据转换,I/O 操作等。
swift
actor SomeActor {
// 不允许
@concurrent
func doSomething() async throws {
}
// 允许
@concurrent
nonisolated func doAnotherthing() async throws {
}
}