티스토리 뷰
iOS Swift + UIKit
iOS Swift withTaskGroup, withThrowingTaskGroup 비동기 반복문 (async await loop)
GonsLab 2025. 4. 1. 00:00728x90
반응형
func test() async {
await withTaskGroup(of: Int.self) { taskGroup in
[3,1,2].forEach { i in
taskGroup.addTask {
print("시작 \(i)")
try? await Task.sleep(for: .seconds(i))
return i
}
}
for await element in taskGroup {
print("완료 \(element)")
}
}
print("모두 완료")
}
Task {
await test()
}
/*
시작 3
시작 1
시작 2
한번에 호출되고
1초 후
완료 1
2초 후
완료 2
3초 후
완료 3
모두 완료
*/

func test2() async -> [Int] {
await withTaskGroup(of: Int.self) { taskGroup in
[3,1,2].forEach { i in
taskGroup.addTask {
try? await Task.sleep(for: .seconds(i))
return i
}
}
// TaskGroup 은 AsyncSequence 를 따르기 때문에 reduce 가능
return await taskGroup
.reduce(into: [Int](), { $0.append($1)} )
}
}
Task {
print(await test2())
// 완료된 순서대로 [1, 2, 3] 반환
}
iOS
Swift
Xcode
AsyncSequence
withTaskGroup
withThrowingTaskGroup
async
await
loop
dispatchGroup
728x90
반응형
'iOS Swift + UIKit' 카테고리의 다른 글
iOS UIKit 팝오버 모달 (Popover Modal Tooltip Dropdown) (0) | 2024.11.01 |
---|---|
iOS Swift 배열 개수 자르기 Array Slice (0) | 2023.06.03 |
iOS Swift 클립보드 복사 UIPasteboard 문자열, 이미지 (0) | 2023.03.01 |
iOS Swift 사용자 정의 연산자 Custom Operator (0) | 2023.01.01 |
원티드 프리온보딩 iOS 챌린지 1차 (Wanted Free Onboarding iOS Challenge) (0) | 2022.11.16 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- presentationcompactadaptation
- ios
- 로컬라이징
- AppStore
- 심사
- Xcode
- 인디케이터
- 스위프트
- picker
- 엑스코드
- localizing
- custom segment
- SKPayment
- 아이오에스
- 현지화
- 테이블뷰
- Language
- TabView
- swiftUI
- 리젝
- indicator
- SWIFT
- TabBar
- localizable
- Authorization
- SKProductsRequestDelegate
- 다국어
- Reject
- permission
- 프로그레스
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함