func fetchImage() async throws -> UIImage { /* ... */ }
Task { // 비동기 컨텍스트 시작
do {
let image = try await fetchImage() // await: 현재 태스크를 “일시 중단” 후, 재개
imageView.image = image
} catch {
// 표준 오류 처리
}
}
async로 비동기 함수를 선언하고, 호출 시 await로 일시await는 현재 태스크의 실행을 양보하고, 작업이 끝나면 나중에 같은throws와 자연스럽게 결합되어 예외 흐름이 단순해집니다.@MainActor
final class PhotoViewModel {
func load() async throws {
let (data, _) = try await URLSession.shared.data(from: url)
self.image = UIImage(data: data) // 메인 액터에서 안전하게 UI 상태 갱신
}
}
iOS 15+ SDK는 많은 콜백 기반 API에 async 버전을 제공합니다. 예:
let (data, response) = try await URLSession.shared.data(from: url)
기존 대비 코드가 단순하고 오류/취소 흐름이 일관됩니다.
콜백 기반 함수를 그대로 써야 할 때는 Continuation으로 감쌉니다.
func loadLegacy() async -> String {
await withCheckedContinuation { cont in
legacyAPI { value in
cont.resume(returning: value)
}
}
}
withCheckedContinuation / withCheckedThrowingContinuation은UnsafeContinuation도 존재합니다.let task = Task { try await work() }
task.cancel() // 취소 신호 전파 (협력적)
func work() async throws {
if Task.isCancelled { return } // 직접 체크
try Task.checkCancellation() // 취소면 throw
}
cancel()로 신호를async let 또는withTaskGroup)을 사용합니다.@MainActor로Task.isCancelled 또는 Task.checkCancellation() 확인.\