WWDC - Swift Async 알고리즘 소개
Swift Async 알고리즘 소개 - WWDC22 - 비디오 - Apple Developer
Apple의 최신 오픈 소스 Swift 패키지인 Swift Async 알고리즘을 확인하세요. Zip, Merge 및 Throttle을 비롯하여 AsyncSequence와 함께 사용할 수 있는 이 패키지의 알고리즘을 알아보겠습니다. 이러한...
developer.apple.com
GitHub - apple/swift-async-algorithms: Async Algorithms for Swift
Async Algorithms for Swift. Contribute to apple/swift-async-algorithms development by creating an account on GitHub.
github.com
다중 입력 AsyncSequence로 작동하는 특정 알고리즘들을 갖고 있음
⇒ 이 알고리즘들은 AsyncSequence를 다양한 방식으로 결합
⇒ AsyncSequence가 다중으로 입력되지만 단일 출력된다.
Async Zip
각 베이스에서 결과 튜플을 생성하기 위해 다중 입력을 취하고 그것을 반복함
- Combines values produced into tuples
- Iterates concurrently
- Rethrows failures
for try await (vid,preview) in zip(videos, previews) {
try await upload(vid,preview)
}
Async Merge
- 다양한 AsyncSequence들을 하나의 AsyncSequence로 만들어주는 행위자
- 사용하는 결과가 같아야한다.
for try await in message in merge(primaryAccount.messages, secondaryAccound.meesagges){
displayPreview(message)
}
Async Debounce
- 특정 기간 동안 이벤트가 발생하는 것을 기다린다.
- 실패 시 throw를 즉시 던진다.
- Debounce 알고리즘은 기본적으로 ContinuousClock을 사용한다.
let queries = searchValues.debounce(for: .milliseconds(300)) for await query in queries { let results = try await performSearch(query) await channel.send(results) }
Async Chunks / 스트리밍 매커니즘을 적용할 수 있음
대량의 데이터를 처리할 때 용이한 알고리즘 ⇒ 값을 나누는 일련의 알고리즘
- By count
- By time
- By content
패킷 처리하는 예시 코드:
let batches = outboundMessages.chuncked(by: .repeating(every: .milliseconds(500)))
let encoder = JSONEncoder()
for await batch in batches {
let data = try encoder.encode(batch)
try await postToServer(data)
}
Clock(Protocol) API
Swift 내 새로운 Clock API를 이용함으로써 시간과 작동한다.
- Protocol for defining time
- Defines a way to wake up after a given instant
- Defines a concept of now
ContinuousClock, SuspendingClock
- ContinuousClock ⇒ 스톱워치처럼 시간 측정 시 사용 가능함
- 기기 상태 측정 여부(?)와는 상관 없이 시간은 흘러간다.
- 명확한 기간동안의 딜레이를 주는 경우 사용한다. (human time)
- SuspendingClock ⇒ 시간을 명시적으로 멈출 때 사용
- 기기 상태 측정 여부에 따라 달라진다. (멈춘다.) / (device time)
- 애니메이션을 위한 딜레이가 필요한 상황에서 사용한다.
let clock = SuspendingClock() var deadline = clock.now + .seconds(3) try await clock.sleep(until: deadline)
let suspendingClock = SuspendingClock()
let slapsedSuspending = await clopck.measure {
await someLongRunningWork() // 기기 상태가 background이면 작업을 멈춘다.
}
let continuousClock = ContinuousClock()
let continuousElapsed = await clock.measure {
await someLongRunningWork()
}
AsyncSequence를 사용한 Collection 생성하기
Dicitonary / Set / Array를 구축할 수 있음
struct Att { }
class Hello {
var atts: [Att] = []
func convertCollection<Attatchments: AsyncSequence>(_ attatchments: Attatchments) async rethrows where Attatchments.Element == Att {
self.atts = try await Array(attatchments)
}
}
'이모저모 > Swift' 카테고리의 다른 글
Observable과 ViewModel State에 대한 고찰 (0) | 2025.03.26 |
---|---|
Swift - Task.Sleep vs Timer (0) | 2024.04.30 |
ios - 이미지 중복 사용 방지 처리 (0) | 2024.01.25 |
TaskCounter로 병렬 작업 완료 계수 파악하기 (0) | 2023.12.13 |
UserDefaults with propertyWrapper (0) | 2023.11.30 |
댓글