Swift 5.3 內置於 Xcode 12,新增了多項實用功能。swift
Swift 5.3 以前即便有多個尾隨閉包也只有最後一個能被寫成精簡的形式,這種寫法一個閉包在圓括號內,另外一個在外面。新的寫法把這些閉包都放在圓括號外面,顯得更加簡潔。注意:尾隨閉包中的第一個閉包的標籤會被強制省略。markdown
UIView.animate(withDuration: 0.5) {
// animation code
} completion: { _ in
// completion code
}
複製代碼
struct ContentView: View {
var body: some View {
Button {
print("login")
}
label: {
Text("登陸")
}
}
}
複製代碼
枚舉如今能夠進行比較。閉包
enum Size: Comparable {
case xs
case sm
case md
case lg
}
let small = Size.sm
let large = Size.lg
if small < large {
print("small < large")
}
複製代碼
Swift 5.3 之後,catch 後面能夠捕獲多個異常的值。app
enum FileReadError: Error {
case FileISNull
case FileNotFound
}
func readFileContent(filePath: String) throws -> String {
if filePath == "" {
throw FileReadError.FileISNull
}
if filePath != "/User/Desktop/123.plist" {
throw FileReadError.FileNotFound
}
return "123"
}
do {
let result = try readFileContent(filePath: "abc")
print(result)
} catch FileReadError.FileISNull, FileReadError.FileNotFound { // 同時處理
print("出現錯誤")
} catch {
// 有一個隱含參數 error
print(error)
}
複製代碼
聲明程序的入口點,替換掉之前的@UIApplicationMain
。函數
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
複製代碼
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
複製代碼
之前閉包中引用當前範圍的內容時必須帶上self.
,Swift 5.3 以後若是不產生循環引用能夠省略self.
。這個新特性對 SwiftUI 來講很是友好,由於 SwiftUI 中的 View 保存在值類型的結構體中,因此不會發生循環引用。性能
struct ContentView: View {
@State private var count = 1
var body: some View {
VStack {
Button {
count += 1 // 能夠不用self.count
} label: {
Text("+1")
}
Text("\(count)")
}
}
}
複製代碼
之前在一個屬性中使用 didSet 時,老是調用 getter 來獲取該屬性的 oldValue(即便沒有用到),從而影響性能。Swift 5.3 以後只有在didSet
中使用了oldValue
參數時,getter 纔會被調用。ui
class Person {
var age = 10 {
didSet {
print("age didSet")
}
}
var sex = "男" {
didSet {
print(oldValue) // 使用oldValue
print("sex didSet")
}
}
}
let p = Person()
// 不會調用getter
p.age = 20
// 會調用getter
p.sex = "女"
複製代碼
guard 和 if 語句中的條件能夠按列對齊。spa
guard let x = optionalX,
let y = optionalY else {
}
if let x = optionalX,
let y = optionalY {
}
複製代碼
let number: Float16 = 5.0
複製代碼
提供了 5 種級別:debug
// 1.導入模塊
import os
// 2.建立Logger實例
let logger = Logger()
// 3.使用log函數
logger.log(level: .debug, "test")
logger.log(level: .info, "test")
logger.log(level: .default, "test")
logger.log(level: .error, "test")
logger.log(level: .fault, "test")
複製代碼