WWDC 2021

What‘s new in Swift
Swift 生态提升:

  1. Swift Package Index
  2. Swift Package Collections
  3. Swift System
  4. Swift on Server
  5. Swift DocC,未来支持所有 Swift Projects
  6. Build 提升,局部编译优化,主要针对 SwiftUI
  7. Optimize Object Lifetimes
  8. enum Codable 优化,泛型语法优化<T: X>, .xProperty
  9. propertyWrapper 在 function 中使用
  10. SwiftUI 中使用条件编译优化
#if os(macOS)
.toggleStyle(.checkbox)
#else
.toggleStyle(.switch)
#endif
  1. async/await actor
  2. Swift 6 进行中

What's new in UIKit

  1. 多 window 任务,UIWindowScene
  2. UICollectionView 滑动多选
  3. 提升 keyCommands
  4. Drag and Drap
  5. UIButton.Configuration
  6. TextKit 2
  7. UIScene 恢复状态
  8. cell.configurationUpdateHander
  9. 自定义 copy pause 提示,注重隐私

What's new in Foundation
ARC in Swift: Basics and beyond

/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
///   - x: An instance to preserve until the execution of `body` is completed.
///   - body: A closure to execute that depends on the lifetime of `x` being
///     extended. If `body` has a return value, that value is also used as the
///     return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable public func withExtendedLifetime<T, Result>(_ x: T, _ body: () throws -> Result) rethrows -> Result

Explore WKWebView additions
Your guide to keyboard layout

async await

Task detached, 异步执行任务

func persistentPosts() async throws -> [Post] {       
    typealias PostContinuation = CheckedContinuation<[Post], Error>
    return try await withCheckedThrowingContinuation { (continuation: PostContinuation) in
        self.getPersistentPosts { posts, error in
            if let error = error { 
                continuation.resume(throwing: error) 
            } else {
                continuation.resume(returning: posts)
            }
        }
    }
}

Protect mutable state with Swift actors

每当从外部与 Actor 互动的时候,都是异步进行的。
如果 Actor busy,代码将挂起,CPU 可以进行其他工作。
当 Actor 再次获得资源后,会继续执行。

actor Work {
    var a = 10
    
    func run() -> Int {
        a += 1
        return a
    }
}

let work = Work()
Task {
    print(1, await work.run())
    print(1, await work.a)
}

Task {
    print(2, await work.run())
    print(2, await work.a)
}

// 1 11
// 2 12
// 1 12
// 2 12

如代码中的打印数据

Sendable:
Value Type
Actor Type
不可变的类 (不包含可变属性)
内部执行同步的类(如内部使用 lock 来实现并行)
@Sendable function types, 意味着任何相关的变量都要是 Sendable 的

let a = A()
Task.detached {
    print(Thread.current)
    await a.run()
    print(Thread.current)
}

如果 A 是 Cocoa 或者 UIKit 的子类, 则在执行到 A 的 async 方法时,会自动切换到主线程,并且之后的任务同样在主线程中执行

class A: NSView {
    func run() async {
        print(Thread.current)
    }
}

// <NSThread: 0x60000099c840>{number = 2, name = (null)}
// <_NSMainThread: 0x600000990900>{number = 1, name = main}
// <_NSMainThread: 0x600000990900>{number = 1, name = main}

如果 A 不是和 UI 相关的子类,则不会切回主线程

class A {
    func run() async {
        print(Thread.current)
    }
}

// <NSThread: 0x6000035f0200>{number = 2, name = (null)}
// <NSThread: 0x6000035f0200>{number = 2, name = (null)}
// <NSThread: 0x6000035f0200>{number = 2, name = (null)}

Main Actor:
使用 @MainActor 标记的类,这个类的所有执行都在主线程

@MainActor class A {
    func run() {
        print(Thread.current)
    }
}

// <NSThread: 0x60000293cf40>{number = 2, name = (null)}
// <_NSMainThread: 0x600002958e40>{number = 1, name = main}
// <NSThread: 0x60000293cf40>{number = 2, name = (null)}

nonisolated:
可以使用 nonisolated 来标记某个方法不在主线程执行

@MainActor class A {
    nonisolated func run() {
        print(Thread.current)
    }
}

// <NSThread: 0x600000585a40>{number = 2, name = (null)}
// <NSThread: 0x600000585a40>{number = 2, name = (null)}
// <NSThread: 0x600000585a40>{number = 2, name = (null)}

Explore structured concurrency in Swift
Task Group 的使用

func fetchThumbnails(for ids: [String]) async throws -> [String: UIImage] {
    var thumbnails: [String: UIImage] = [:]
    try await withThrowingTaskGroup(of: (String, UIImage).self) { group in
        for id in ids {
            group.async {
                return (id, try await fetchOneThumbnail(withID: id))
            }
        }
        // Obtain results from the child tasks, sequentially, in order of completion.
        for try await (id, thumbnail) in group {
            thumbnails[id] = thumbnail
        }
    }
    return thumbnails
}

Task detached, 异步执行任务

Task.detached(priority: .background) {
    await withTaskGroup(of: Void.self) { group in
        group.addTask { print(1, Thread.current) }
        group.addTask { await self.run() }
        group.addTask { print(2, Thread.current) }
    }
}

Meet AsyncSequence
异步的 Sequence

let values = AsyncStream(Int.self) { con in
    con.yield(1)
    con.yield(2)
    con.yield(3)
}

for await i in values {
    print(i)
}

Swift concurrency: Behind the scenes

Cooperative thread pool:
控制线程数量不大于 CPU 数量,避免线程过多造成的上下文频繁切换。

await 和 原子:
await 不要持有任何锁。
线程私有数据也不会在 await 过程中保留。
async/await 对比锁的优势,编译期间,编译器会帮助检查使用的正确性。
在 await 中使用锁要非常小心。
不要在 await 中使用信号量, 如下代码:sem.signal 永远执行不到。

func run1() async {
    print(3, Thread.current)
}

override func viewDidLoad() {
    super.viewDidLoad()
    
    let sem = DispatchSemaphore(value: 0)
    Task.detached {
        await self.run1()
        sem.signal()
    }
    sem.wait()
}

SwiftUI:

What's new in SwiftUI
SwiftUI Accessibility: Beyond the basics
Direct and reflect focus in SwiftUI
Localize your SwiftUI app
Bring Core Data concurrency to Swift and SwiftUI
Discover concurrency in SwiftUI
Demystify SwiftUI

Development

Meet TestFlight on Mac
Meet Xcode Cloud
Explore Xcode Cloud workflows
Customize your advanced Xcode Cloud workflows
Review code and collaborate in Xcode
Distribute apps in Xcode with cloud signing
Meet the Swift Algorithms and Collections packages

New:

Capture high-quality photos using video formats
Design for Group Activities
Extract document data using Vision
Discover Web Inspector improvements
Develop advanced web content
Create image processing apps powered by Apple Silicon
Build custom experiences with Group Activities
What’s new in camera capture
What's new in Wallet and Apple Pay
What's new in App Analytics
Secure login with iCloud Keychain verification codes
Qualities of great iPad and iPhone apps on Macs with M1
Improve global streaming availability with HLS Content Steering
Explore low-latency video encoding with VideoToolbox
Support customers and handle refunds
Manage in-app purchases on your server

Test:

Triage TestFlight crashes in Xcode Organizer
Explore Digital Crown, Trackpad, and iPad pointer automation
Embrace Expected Failures in XCTest
Diagnose unreliable code with test repetitions
Detect and diagnose memory issues
Ultimate application performance survival guide
Analyze HTTP traffic in Instruments

Doc

Host and automate your DocC documentation
Build interactive tutorials using DocC
Meet DocC documentation in Xcode

Design

What’s new in SF Symbols
Explore the SF Symbols 3 app
Create custom symbols
Symbolication: Beyond the basics

Watch

Connect Bluetooth devices to Apple Watch

3D

Create 3D models with Object Capture

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,753评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,668评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,090评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,010评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,054评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,806评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,484评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,380评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,873评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,021评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,158评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,838评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,499评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,044评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,159评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,449评论 3 374
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,136评论 2 356