簡版 Swift 5.7 新特性一覽
Swift 5.7 引入了一個(gè)巨大的語言更改和改進(jìn)集合,包括正則表達(dá)式等強(qiáng)大功能,if let 速記語法等生活質(zhì)量改進(jìn),以及圍繞 any 和 some 關(guān)鍵字的大量一致性清理。
在本文中,我們精簡了 HACKING WITH SWIFT 的 《What’s new in Swift 5.7》一文,讓大家能快速了解 Swift 5.7 的主要變化,并在此過程中提供一些動(dòng)手示例,以便您自己了解發(fā)生了什么變化。
重要提示:這些變化中有許多是復(fù)雜的,其中許多也是相互關(guān)聯(lián)的。如果想了解更詳細(xì)的內(nèi)容,可以查看原文或直接查看 SE 文檔。
if let 簡化語法
來源:SE-0345 https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md
目標(biāo):用于將 Optional 值解包到同名的影子變量中
var name: String? = "Linda"// beforeif let unwrappedName = name {print("Hello, \(unwrappedName)!")}
=>// Swift 5.7if let name { print("Hello, \(name)!")}
多語句閉包類型推斷
來源:SE-0326 https://github.com/apple/swift-evolution/blob/main/proposals/0326-extending-multi-statement-closure-inference.md
目標(biāo):提高 Swift 對閉包使用參數(shù)和類型推斷的能力
結(jié)果:現(xiàn)在可以刪除許多必須明確指定輸入和輸出類型的地方
let scores = [100, 80, 85]// beforelet oldResults = scores.map { score -> String in
if score >= 85 {return "\(score)%: Pass"
} else {return "\(score)%: Fail"}
}// Swift 5.7let results = scores.map { score in
if score >= 85 {return "\(score)%: Pass"
} else {return "\(score)%: Fail"}
}
Clock, Instant 和 Duration
來源:SE-0329 https://github.com/apple/swift-evolution/blob/main/proposals/0329-clock-instant-duration.md
目標(biāo):以標(biāo)準(zhǔn)化的方式來引用 Swift 中的時(shí)間和持續(xù)時(shí)間
結(jié)果:三種時(shí)間定義
Clocks:表示一種測量時(shí)間流逝的方式;
Instants:表示一個(gè)確切的時(shí)刻;
Durations:表示兩個(gè) instants 之間經(jīng)過了多少時(shí)間
// 新的 Task APItry await Task.sleep(until: .now + .seconds(1), clock: .continuous)try await Task.sleep(until: .now + .seconds(1), tolerance: .seconds(0.5), clock: .continuous)
正則表達(dá)式
來源:
SE-0350:https://github.com/apple/swift-evolution/blob/main/proposals/0350-regex-type-overview.md
SE-0351:https://github.com/apple/swift-evolution/blob/main/proposals/0351-regex-builder.md
SE-0354:https://github.com/apple/swift-evolution/blob/main/proposals/0354-regex-literals.md
SE-0357:https://github.com/apple/swift-evolution/blob/main/proposals/0357-regex-string-processing-algorithms.md
目標(biāo):改進(jìn)處理字符串的方式
結(jié)果:
引入了一種新的 Regex 類型
引入了一個(gè)結(jié)果生成器驅(qū)動(dòng)的 DSL 來創(chuàng)建正則表達(dá)式
添加了使用 /.../ 創(chuàng)建正則表達(dá)式的能力,而不是通過正則表達(dá)式和字符串
添加了許多基于正則表達(dá)式的新字符串處理算法
示例 1:可使用的新字符串方法
let message = "the cat sat on the mat"print(message.ranges(of: "at"))print(message.replacing("cat", with: "dog"))print(message.trimmingPrefix("the "))// 同時(shí)也可使用正則表達(dá)式print(message.ranges(of: /[a-z]at/))print(message.replacing(/[a-m]at/, with: "dog"))print(message.trimmingPrefix(/The/.ignoresCase()))
示例 2:Regex 類型
do {let atSearch = try Regex("[a-z]at")print(message.ranges(of: atSearch))
} catch {print("Failed to create regex")}
示例 3:DSL 語法創(chuàng)建正則表達(dá)式
let search3 = Regex {"My name is "
Capture {OneOrMore(.word)
}" and I'm "
Capture {OneOrMore(.digit)
}" years old."}
示例 4:TryCapture(捕獲失敗或拋出錯(cuò)誤,Swift 將自動(dòng)認(rèn)為整個(gè)正則表達(dá)式不匹配)
let search4 = Regex {"My name is "
Capture {OneOrMore(.word)
}" and I'm "
TryCapture {OneOrMore(.digit)} transform: { match in
Int(match)
}Capture(.digit)" years old."}
示例 5:使用具有特定類型的變量將命名匹配組合在一起
let nameRef = Reference(Substring.self)let ageRef = Reference(Int.self)let search5 = Regex {"My name is "
Capture(as: nameRef) {OneOrMore(.word)
}" and I'm "
TryCapture(as: ageRef) {OneOrMore(.digit)} transform: { match in
Int(match)
}Capture(.digit)" years old."}if let result = greeting.firstMatch(of: search5) {print("Name: \(result[nameRef])")print("Age: \(result[ageRef])")}
從默認(rèn)表達(dá)式進(jìn)行類型推斷
來源:SE-0347 https://github.com/apple/swift-evolution/blob/main/proposals/0347-type-inference-from-default-exprs.md
目標(biāo):擴(kuò)展 Swift 使用泛型參數(shù)類型的默認(rèn)值的能力
結(jié)果:如果你有一個(gè)泛型類型或函數(shù),你現(xiàn)在可以為默認(rèn)表達(dá)式提供一個(gè)具體類型
func drawLotto1<T: Sequence>(from options: T, count: Int = 7) -> [T.Element] {Array(options.shuffled().prefix(count))
}print(drawLotto1(from: 1...49))print(drawLotto1(from: ["Jenny", "Trixie", "Cynthia"], count: 2))// => Swift 5.7// T 參數(shù)的默認(rèn)值 1...49func drawLotto2<T: Sequence>(from options: T = 1...49, count: Int = 7) -> [T.Element] {Array(options.shuffled().prefix(count))
}print(drawLotto2(from: ["Jenny", "Trixie", "Cynthia"], count: 2))print(drawLotto2())
頂層代碼中的并發(fā)
來源:SE-0343 https://github.com/apple/swift-evolution/blob/main/proposals/0343-top-level-concurrency.md
目標(biāo):升級(jí) Swift 對頂層代碼的支持,支持開箱即用的并發(fā)
// 將以下代碼放入 main.swift 中let url = URL(string: "https://hws.dev/readings.json")!let (data, _) = try await URLSession.shared.data(from: url)let readings = try JSONDecoder().decode([Double].self, from: data)print("Found \(readings.count) temperature readings")
不透明的參數(shù)聲明
來源:SE-0341 https://github.com/apple/swift-evolution/blob/main/proposals/0341-opaque-parameters.md
目標(biāo):解鎖在使用更簡單泛型的地方使用參數(shù)聲明的能力
結(jié)果:[some Comparable] 參數(shù)類型 (函數(shù)可以與包含符合 Comparable 協(xié)議的一種類型的元素的數(shù)組一起使用)
func isSortedOld<T: Comparable>(array: [T]) -> Bool {
array == array.sorted()
}// => Swift 5.7func isSorted(array: [some Comparable]) -> Bool {array == array.sorted()
}// Tip: 可以在顯式泛型參數(shù)和這種新的更簡單語法之間切換,而不會(huì)破壞您的 API
結(jié)構(gòu)不透明的結(jié)果類型
來源:SE-0328 https://github.com/apple/swift-evolution/blob/main/proposals/0328-structural-opaque-result-types.md
目標(biāo):擴(kuò)大不透明結(jié)果類型可以使用的地方范圍
// Swift 5.7func showUserDetails() -> (some Equatable, some Equatable) {(Text("Username"), Text("@twostraws"))
}func createUser() -> [some View] {let usernames = ["@frankefoster", "@mikaela__caron", "@museumshuffle"]return usernames.map(Text.init)
}func createDiceRoll() -> () -> some View {return {let diceRoll = Int.random(in: 1...6)return Text(String(diceRoll))}
}
為所有協(xié)議解鎖 existentials
來源:SE-0309 https://github.com/apple/swift-evolution/blob/main/proposals/0309-unlock-existential-types-for-all-protocols.md
目標(biāo):放寬 Swift 對在具有 Self 或關(guān)聯(lián)類型要求時(shí)將協(xié)議用作類型的禁令,轉(zhuǎn)向僅基于特定屬性或方法不受限制的模型
// Swift 5.7 之后合法let tvShow: [any Equatable] = ["Brooklyn", 99]for parts in tvShow {if let item = item as? String {print("Found string: \(item)")
} else if let item = item as? Int {print("Found integer: \(item)")}
}
主要關(guān)聯(lián)類型的輕量級(jí)同類型要求
來源:SE-0346 https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md
結(jié)果:添加了更新、更簡單的語法來引用具有特定關(guān)聯(lián)類型的協(xié)議
protocol Cache<Content> {
associatedtype Content
var items: [Content] { get set }init(items: [Content])mutating func add(item: Content)}struct File {let name: String}struct LocalFileCache: Cache {var items = [File]()mutating func add(item: File) {items.append(item)
}
}func loadDefaultCache() -> LocalFileCache {LocalFileCache(items: [])
}// beforefunc loadDefaultCacheOld() -> some Cache {LocalFileCache(items: [])
}// Swift 5.7func loadDefaultCacheNew() -> some Cache<File> {LocalFileCache(items: [])}
分布式 actor isolation
來源:
SE-0336: https://github.com/apple/swift-evolution/blob/main/proposals/0336-distributed-actor-isolation.md
SE-0344:https://github.com/apple/swift-evolution/blob/main/proposals/0344-distributed-actor-runtime.md
目標(biāo):引入 actor 以分布式形式工作的能力——使用遠(yuǎn)程過程調(diào)用 (RPC) 通過網(wǎng)絡(luò)讀取和寫入屬性或調(diào)用方法。
// use Apple's ClusterSystem transporttypealias DefaultDistributedActorSystem = ClusterSystemdistributed actor CardCollector {var deck: Set<String>init(deck: Set<String>) {self.deck = deck}
distributed func send(card selected: String, to person: CardCollector) async -> Bool {guard deck.contains(selected) else { return false }do {try await person.transfer(card: selected)
deck.remove(selected)return true
} catch {return false}
}
distributed func transfer(card: String) {
deck.insert(card)
}
}
用于結(jié)果構(gòu)建器的 buildPartialBlock
來源:SE-0348 https://github.com/apple/swift-evolution/blob/main/proposals/0348-buildpartialblock.md
目標(biāo):簡化實(shí)現(xiàn)復(fù)雜結(jié)果構(gòu)建器所需的重載
結(jié)果:
Swift 高級(jí)正則表達(dá)式支持成為可能
取消了 SwiftUI 的 10-view 限制,而無需添加可變參數(shù)泛型
@resultBuilderstruct SimpleViewBuilderOld {static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View {TupleView((c0, c1))
}static func buildBlock<C0, C1, C2>(_ c0: C0, _ c1: C1, _ c2: C2) -> TupleView<(C0, C1, C2)> where C0: View, C1: View, C2: View {TupleView((c0, c1, c2))}
}// => // Swift 5.7@resultBuilderstruct SimpleViewBuilderNew {static func buildPartialBlock<Content>(first content: Content) -> Content where Content: View {content
}static func buildPartialBlock<C0, C1>(accumulated: C0, next: C1) -> TupleView<(C0, C1)> where C0: View, C1: View {TupleView((accumulated, next))}
}
隱式打開的 existentials
來源:SE-0352 https://github.com/apple/swift-evolution/blob/main/proposals/0352-implicit-open-existentials.md
目標(biāo):允許 Swift 在許多情況下使用協(xié)議調(diào)用泛型函數(shù),以消除以前存在的一個(gè)有點(diǎn)奇怪的障礙。
func double<T: Numeric>(_ number: T) -> T {
number * 2}let first = 1let second = 2.0let third: Float = 3let numbers: [any Numeric] = [first, second, third]for number in numbers {print(double(number))}
Swift snippets
來源:SE-0356 https://github.com/apple/swift-evolution/blob/main/proposals/0356-swift-snippets.md
目標(biāo):填補(bǔ)項(xiàng)目的一個(gè)小而重要的文檔空白:示例代碼大于簡單的 API 文檔,但小于示例項(xiàng)目,旨在展示項(xiàng)目中的一個(gè)特定內(nèi)容。
結(jié)果:使用 // MARK: Hide 和 // MARK: Show 隱藏一些實(shí)現(xiàn)細(xì)節(jié),讓讀者專注于重要的部分
//! Demonstrates how to use conditional conformance//! to add protocols to a data type if it matches//! some constraint.struct Queue<Element> {private var array = [Element]()// MARK: Hide
mutating func append(_ element: Element) {
array.append(element)
}mutating func dequeue() -> Element? {guard array.count > 0 else { return nil }return array.remove(at: 0)
}// MARK: Show}extension Queue: Encodable where Element: Encodable { }extension Queue: Decodable where Element: Decodable { }extension Queue: Equatable where Element: Equatable { }extension Queue: Hashable where Element: Hashable { }let queue1 = Queue<Int>()let queue2 = Queue<Int>()print(queue1 == queue2)
異步屬性不可用
來源:SE-0340 https://github.com/apple/swift-evolution/blob/main/proposals/0340-swift-noasync.md
目標(biāo):將類型和函數(shù)標(biāo)記為在異步上下文中不可用,因?yàn)橐赃@種方式使用它們可能會(huì)導(dǎo)致問題,從而部分關(guān)閉了 Swift 并發(fā)模型中的潛在風(fēng)險(xiǎn)情況。
結(jié)果:要將某些內(nèi)容標(biāo)記為在異步上下文中不可用,請?jiān)谡_x擇的平臺(tái)中使用 @available,然后將 noasync 添加到末尾。
@available(*, noasync)func doRiskyWork() {
}其它
SE-0349: Unaligned Loads and Stores from Raw Memory
SE-0334: Pointer API Usability Improvements
SE-0333: Expand usability of withMemoryRebound
SE-0338: Clarify the Execution of Non-Actor-Isolated Async Functions
SE-0360: Opaque result types with limited availability
慢慢看,太難了

面試題】即可獲取