Swift 6.2 内置于 Xcode 26,主要带来了如下的新特性。
显著扩展了创建标识符的字符范围,当使用``时,可以更随性。
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
时,可以使用提供的默认值。
var name: String? = nil
// Swift6.2之前
print("Hello, \(name ?? "zhangsan")!")
// Swift6.2之后
print("Hello, \(name, default: "zhangsan")!")
引入了一种新的数组类型,表示固定大小的数组,性能优越。
var array: InlineArray<3, String> = ["zhangsan", "lisi", "wangwu"]
var array2: InlineArray = ["zhangsan", "lisi", "wangwu"]
进一步简化了在 SwiftUI 中的使用。
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
,允许声明不可变的弱引用属性。import UIKit
class ViewController: UIViewController {
// Swift6.2之前
@IBOutlet weak var redView: UIView!
// Swift6.2之后
@IBOutlet weak let greenView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
引入了一个新的结构体,提供运行时堆栈追踪,可以捕获从当前代码处到调用处的函数调用序列。
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()
@concurrent
进行修饰,可以继续让其按照之前的方式运行。@concurrent
时,函数会发生以下行为。 actor SomeActor {
// 不允许
@concurrent
func doSomething() async throws {
}
// 允许
@concurrent
nonisolated func doAnotherthing() async throws {
}
}