[SE-0442] Allow TaskGroup's ChildTaskResult Type To Be Inferred
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0442
- 상태: Implemented (Swift 6.1)
- upcoming feature flag: 없음
- 저자: Richard L Zarth III
- 리뷰 매니저: Doug Gregor
- 구현: apple/swift#74517
- pitch: Pitch (2024-05-30)
- 리뷰: Review (2024-07-23 시작, 08-06 까지)
- 수락: Accepted (2024-08-06, 제안서 그대로 수락)
- 관련 제안서: SE-0420 (
isolation:매개변수와#isolation), SE-0431 (addTask의@isolated(any))
수락 공지의 링크 주소에는 accepted-se-0422 라고 적혀 있다. 번호가 잘못 들어간 주소이고, 가리키는 글은 SE-0442 의 수락 공지다.
한 줄 요약
withTaskGroup 과 withThrowingTaskGroup 의 of: 인자에 = ChildTaskResult.self 기본값을 넣어서, closure 안에서 group 을 처음 쓰는 addTask 의 반환 타입으로 자식 task 의 결과 타입(ChildTaskResult)을 컴파일러가 추론하게 한다. 소스와 ABI 를 깨지 않고, 기존의 of: 는 그대로 쓸 수 있다.
어떤 문제였나
task group 을 만들 때 쓰는 withTaskGroup(of:returning:body:) 에는 타입 인자가 둘 있다. 하나는 GroupResult 로, group 을 쓴 뒤 body 가 돌려주는 값의 타입이다. 이쪽은 body 의 return 에서 컴파일러가 알아낼 수 있어서 처음부터 적지 않아도 됐다. 다른 하나는 자식 task 가 돌려주는 값의 타입인 ChildTaskResult 인데, 이쪽은 of: Message.self 처럼 항상 직접 적어야 했다. 이 글에서 다루는 SE-0442 는 그 비대칭을 없애는 제안이다. 글의 무게는 두 곳에 둔다. 컴파일러가 closure 본문의 어느 문장에서 ChildTaskResult 를 정하는지, 그리고 어디서 막히는지다. 제안서는 짧지만 이 두 가지는 6.4 컴파일러로 하나씩 돌려 봐야 모양이 보인다.
앞 글들에서 task group 이 예제 속에 나온 적은 있지만 task group 자체를 풀어 쓴 적은 없다. 먼저 task group 이 무엇인지 짚고 간다.
- SE-0414 글:
withTaskGroup안에서 non-Sendable iterator 를 쓰는 예제(리뷰 #14) - SE-0434 글:
withDiscardingTaskGroup에 자식 task 둘을 보내는 예제 - SE-0430 글:
addTask의operation이sendingclosure 인 이유 - SE-0431 글: 그
operation이@isolated(any)인 이유
task group 다시 보기
task group 은 여러 일을 동시에 시켜 놓고 결과를 모아 받는 도구다. 식당 주방에 비유하면, 주문(addTask)을 여러 개 넣으면 요리사들이 각자 동시에 만들고, 홀 직원(for await)은 끝나는 순서대로 접시를 하나씩 받는다. 주방이 문을 닫으려면 모든 요리가 끝나야 한다. 취소된 주문도 요리사가 손을 뗄 때까지 기다린다. task group 은 SE-0304 (structured concurrency) 가 도입했고 Swift 5.5 에 들어왔다. “구조화” 라는 말은 group 안에서 만든 자식 task 가 withTaskGroup 호출이 끝나기 전에 모두 끝난다는 뜻이다.
가장 흔한 모양은 id 마다 자식 task 하나를 만들어 다운로드하고, 끝난 것부터 모으는 것이다. 제안서 Motivation 의 예제를 6.4 에서 빌드되게 옮겼다. 이 글의 코드는 모두 Message 타입과 아래 두 함수를 같이 컴파일한다.
1
2
3
struct Message: Sendable { let id: Int }
func downloadMessage(for id: Int) async -> Message { Message(id: id) }
func logMessageReceived(for id: Int) async {}
1
2
3
4
5
6
7
8
9
10
11
12
13
func explicit(ids: [Int]) async -> [Message] {
await withTaskGroup(of: Message.self) { group in
for id in ids {
group.addTask { await downloadMessage(for: id) }
}
var messages: [Message] = []
for await message in group {
messages.append(message)
}
return messages
}
}
withTaskGroup 으로 자식 task 를 모으기
withTaskGroup(of:returning:isolation:body:) 은 TaskGroup 을 만들어 body closure 에 넘기고, body 가 돌려준 값을 그대로 돌려주는 함수다. group 은 body 가 끝나는 순간 사라지므로 밖으로 꺼내 쓸 수 없다. with... 라는 이름이 붙은 이유다.
TaskGroup.addTask(priority:operation:)은 자식 task 를 하나 만들어 곧바로 실행을 시작한다.operation이 돌려주는 값이 그 자식 task 의 결과다. 위 코드에서는Message다.for await message in group은 group 에AsyncSequence로 접근해서 자식 task 가 끝나는 대로 결과를 하나씩 받는다. 시작한 순서가 아니라 끝난 순서이고, 자식이 다 끝나면 반복이 멈춘다.for await가 안쪽에서 부르는TaskGroup.next()를 직접 부르면 결과 하나를 받고, 더 받을 것이 없으면nil을 준다.TaskGroup.cancelAll()은 group 안의 모든 자식 task 에 취소를 알린다. 취소는 “그만해 달라” 는 요청이라서, 자식이 취소를 확인해야 멈춘다. 이후에addTask로 더한 task 도 처음부터 취소된 상태로 시작한다.TaskGroup.isCancelled는 group 이 취소되었는지 보여 주는 프로퍼티다.TaskGroup.addTaskUnlessCancelled(priority:operation:)는 group 이 이미 취소된 뒤면 task 를 더하지 않고false를 돌려준다.withThrowingTaskGroup은 자식 task 가throws일 수 있는 짝이다. 자식이 던진 error 는for try await나try await group.next()에서 나온다.withDiscardingTaskGroup은 자식 결과를 모으지 않고 버리는 group 이다. SE-0381 이 도입했다. 이 글의 주제와 이어지는 이유는 아래 “Void 자식 결과” 에서 나온다.
body 의 매개변수가 inout TaskGroup<ChildTaskResult> 인 점도 짚어 둔다. inout 은 함수 안에서 인자를 직접 고칠 수 있게 넘긴다는 표시다. addTask 는 group 을 바꾸는 mutating 메서드이므로 group 은 body 안에서 inout 으로 쓰인다.
ChildTaskResult 와 GroupResult 란?
TaskGroup<ChildTaskResult> 의 꺾쇠 안에 든 것은 generic 매개변수다. 상자에 붙이는 라벨이라고 생각하면 된다. TaskGroup<Message> 는 “Message 를 담는 task group” 이고 TaskGroup<Int> 는 “Int 를 담는 task group” 이다. 컴파일러는 라벨을 보고 for await 로 받는 값이 Message 인지 Int 인지 안다. 그 라벨을 코드에 직접 적지 않아도 앞뒤 코드에서 컴파일러가 알아내는 것을 타입 추론이라고 한다. let x = 3 이라고만 써도 x 가 Int 인 것이 타입 추론이다.
withTaskGroup 에는 이 라벨이 둘 있다.
| 이름 | 뜻 | 위 예제에서 |
|---|---|---|
ChildTaskResult | 자식 task 하나가 돌려주는 값의 타입. group 의 라벨이다 | Message |
GroupResult | body 가 돌려주는 값, 곧 withTaskGroup 호출 전체의 결과 타입 | [Message] |
둘은 서로 다른 것이다. 자식은 Message 를 하나씩 돌려주고, body 는 그것을 모아 [Message] 한 개를 돌려준다. 같은 타입일 수도, 한쪽이 Void 일 수도, 둘 다 Void 일 수도 있다.
of 인자를 꼭 적어야 했던 이유
6.4 SDK 의 _Concurrency 모듈 인터페이스에서 withTaskGroup 선언을 읽으면 이렇다.
1
2
3
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@backDeployed(before: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0)
@inlinable public func withTaskGroup<ChildTaskResult, GroupResult>(of childTaskResultType: ChildTaskResult.Type = ChildTaskResult.self, returning returnType: GroupResult.Type = GroupResult.self, isolation: isolated (any _Concurrency::Actor)? = #isolation, body: (inout _Concurrency::TaskGroup<ChildTaskResult>) async -> GroupResult) async -> GroupResult where ChildTaskResult : Swift::Sendable
지금은 두 매개변수에 모두 기본값이 있다. 제안서가 보인 당시 선언은 of childTaskResultType: ChildTaskResult.Type 에 기본값이 없었다. 반면 바로 아래 returning returnType: GroupResult.Type = GroupResult.self 에는 처음부터 기본값이 있었다. 같은 기법을 한쪽에만 쓰고 있었던 것이다. 피치를 연 rlziii 가 첫 글(#1)에서 이 점을 짚었다. SE-0304 를 읽어 봐도 이 API 가 일부러 그렇게 설계됐다는 내용이 없었다는 것이다. 그가 제안한 변경은 of: 에 = ChildTaskResult.self 를 더하는 한 줄이다.
메타타입 기본 인자로 타입 추론시키기
ChildTaskResult.Type 은 타입 자체를 값으로 다루는 메타타입이고, ChildTaskResult.self 는 그 값을 만드는 표현이다. of: Message.self 를 쓰는 이유는 컴파일러에게 “라벨은 Message” 라고 직접 알려 주려는 것이다. 매개변수에 기본값 = ChildTaskResult.self 를 두면, 호출하는 쪽이 of: 를 생략했을 때 기본값이 ChildTaskResult 자신이 되어 라벨이 다른 곳(여기서는 body closure 의 본문)에서 정해지기를 기다린다. 기본값이 없으면 호출할 때 of: 가 필수라서 이 길이 열리지 않는다.
나머지 attribute 와 매개변수는 이렇다.
@inlinable은 함수 본문을 모듈 밖의 호출자 쪽으로 복사해 넣을 수 있게 하는 표시다.@backDeployed(before: macOS 15.0, ...)는 OS 가 이 함수를 갖고 있지 않은 옛 버전에서는 앱 쪽에 복사된 본문이 대신 돌게 하는 표시다. 이 attribute 는isolation:매개변수와 관련 있어서, 아래 “배포 대상 OS” 에서 다시 본다.isolation: isolated (any Actor)? = #isolation은 SE-0420 이 도입한 매개변수다. 호출한 쪽의 actor 가#isolation으로 자동으로 넘어와서, group 의body가 호출한 쪽 isolation 에서 돈다. SE-0420 글에서 풀었으므로 여기서는 이 제안과 별개인 매개변수라는 것만 짚는다.where ChildTaskResult : Sendable은 자식 결과가Sendable이어야 한다는 제약이다. 자식 task 가 만든 값이 task 경계를 넘어body로 전달되기 때문이다.
그러면 왜 SE-0304 때는 ChildTaskResult 에 기본값을 못 넣었을까. 피치에서 ktoso 가 팀과 함께 살펴본 답이 있다(#17). task group 은 Swift 5.5 에 들어왔고, 이 추론이 가능해진 근거인 SE-0326 (multi-statement closure 타입 추론 확장)은 5.7 에 들어왔는데 그때 task group 에 적용할 수 있다는 것을 놓쳤다는 설명이다. 리뷰에서도 ktoso 는 SE-0326 이후 가능해진 개선이라고 썼다(리뷰 #7). 여러 문장짜리 closure 의 본문을 위에서 아래로 보면서 타입을 정하는 규칙이 있어야 addTask 가 들어 있는 for 문 속에서 ChildTaskResult 를 정할 수 있다.
Void.self 를 적는 일
가장 거슬리는 경우는 자식 결과가 없을 때다. 제안서 Motivation 은 이 예제를 든다.
1
2
3
4
5
6
7
8
9
func logCount(ids: [Int]) async -> Int {
await withTaskGroup(of: Void.self) { group in
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
return ids.count
}
}
(위 코드는 제안서의 logCount 를 함수로 감싼 것이다. 아래 Motivation.swift 에는 of: 를 뺀 판이 들어 있다.)
자식은 결과가 없어서 Void 이고 body 는 Int 를 돌려준다. 제안서는 of: 에 들어갈 올바른 타입이 처음 쓰는 사람에게 직관적이지 않을 수 있다고 쓴다. 자식 결과가 없는 이 자리에서는 Void.self 가 그렇다. of: 를 틀리게 적으면 컴파일러가 무엇을 알려 주는지 6.4 에서 돌려 봤다. Void.self 대신 Int.self 를 적은 판이다(LogCount.swift).
1
2
3
4
5
6
7
8
9
func logCountInt(ids: [Int]) async -> Int {
await withTaskGroup(of: Int.self) { group in
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
return ids.count
}
}
1
2
3
4
5
6
7
LogCount.swift:13:23: error: cannot convert value of type '()' to closure result type 'Int'
11 | await withTaskGroup(of: Int.self) { group in
12 | for id in ids {
13 | group.addTask { await logMessageReceived(for: id) }
| `- error: cannot convert value of type '()' to closure result type 'Int'
14 | }
15 |
error 는 withTaskGroup 이 아니라 addTask 의 closure(13:23)에 붙고, 자식이 () 를 돌려주는데 Int 를 기대한다는 말만 한다. of: 의 타입을 고치라고 이끄는 문구는 없다. 어디가 틀렸는지는 알려 주지만 of: 에 무엇을 적어야 하는지는 직접 알아내야 한다.
리뷰에서 grynspan 은 withTaskGroup(of: Void.self) 를 수없이 썼다며 추론을 허용하자고 했다(리뷰 #14). 이어서 vns 가 withDiscardingTaskGroup 이 Void 경우를 다루지 않느냐고 물었고(#15), grynspan 은 Void 는 예시였다고 답했다(#16). 피치에서 ktoso 는 이 모양이 보기 싫어서 withDiscardingTaskGroup 을 쓸 생각을 하게 만드는 효과도 있었다고 했다(#8). 다만 일부러 더 보기 싫게 둘 생각은 없다고 덧붙였다.
무엇이 바뀌나
of childTaskResultType: ChildTaskResult.Type 에 = ChildTaskResult.self 기본값을 더한다. withTaskGroup 과 withThrowingTaskGroup 둘에 적용되고, 다른 것은 바뀌지 않는다. withDiscardingTaskGroup 과 withThrowingDiscardingTaskGroup 은 자식 결과가 항상 Void 라서 처음부터 ChildTaskResult 가 없다. 6.4 SDK 에서 이 둘의 선언은 이렇다.
1
@inlinable public func withDiscardingTaskGroup<GroupResult>(returning returnType: GroupResult.Type = GroupResult.self, isolation: isolated (any _Concurrency::Actor)? = #isolation, body: (inout _Concurrency::DiscardingTaskGroup) async -> GroupResult) async -> GroupResult {
1
@inlinable public func withThrowingDiscardingTaskGroup<GroupResult>(returning returnType: GroupResult.Type = GroupResult.self, isolation: isolated (any _Concurrency::Actor)? = #isolation, body: (inout _Concurrency::ThrowingDiscardingTaskGroup<any Swift::Error>) async throws -> GroupResult) async throws -> GroupResult {
withThrowingTaskGroup 은 withTaskGroup 과 같은 모양에 ThrowingTaskGroup<ChildTaskResult, any Swift::Error> 를 받고 async rethrows 다. 아래부터는 withTaskGroup 위주로 보고, throwing 은 따로 한 번 돌려 본다. 아래 진단은 Swift 5, Swift 5 + -strict-concurrency=complete, Swift 6 세 언어 모드로 모두 돌렸고, 따로 적지 않은 것은 세 모드 결과가 같다. 진단은 모두 -emit-sil 로 뽑았다.
기본 인자 하나
Motivation.swift 의 inferred 는 앞의 explicit 에서 of: 만 뺀 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func inferred(ids: [Int]) async -> [Message] {
await withTaskGroup { group in
for id in ids {
group.addTask { await downloadMessage(for: id) }
}
var messages: [Message] = []
for await message in group {
messages.append(message)
}
return messages
}
}
func logCount(ids: [Int]) async -> Int {
await withTaskGroup { group in
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
return ids.count
}
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Motivation.swift
-emit-sil 은 타입 검사 뒤 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계에서 나오는 진단까지 모두 낸다. -o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 최상위 코드가 없는 소스로 다루게 하며, -wmo 는 모든 파일을 한 모듈로 같이 컴파일한다. 이 명령의 진단은 0 개다. 컴파일러는 explicit 과 같은 일을 of: 없이 해 낸다. group.addTask { await downloadMessage(for: id) } 의 closure 가 Message 를 돌려주므로 ChildTaskResult 는 Message 이고, body 의 마지막 return messages 가 [Message] 이므로 GroupResult 는 [Message] 다. logCount 는 자식 closure 가 아무것도 돌려주지 않아서 ChildTaskResult 는 Void, return ids.count 때문에 GroupResult 는 Int 다. 같은 withTaskGroup 호출 하나에서 두 타입이 서로 다른 문장에서 정해진다.
실제로 정해진 타입을 보려고 Kinds.swift 를 실행 파일로 만들었다. type(of:) 로 group 과 결과의 타입을 찍는다.
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
@main
struct App {
static func main() async {
let messages = await withTaskGroup { group in
for id in 1...3 {
group.addTask { await downloadMessage(for: id) }
}
print("group:", type(of: group))
var result: [Message] = []
for await m in group { result.append(m) }
return result.sorted { $0.id < $1.id }
}
print("messages:", type(of: messages), messages.map(\.id))
let count = await withTaskGroup { group in
for id in 1...3 {
group.addTask { await logMessageReceived(for: id) }
}
print("group:", type(of: group))
return 3
}
print("count:", type(of: count), count)
let empty: Void = await withTaskGroup { group in
group.addTask {}
print("group:", type(of: group))
}
print("empty:", type(of: empty))
}
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Kinds.swift -o kinds
./kinds
1
2
3
4
5
6
group: TaskGroup<Message>
messages: Array<Message> [1, 2, 3]
group: TaskGroup<()>
count: Int 3
group: TaskGroup<()>
empty: ()
type(of:) 로 추론된 타입 찍어 보기
type(of:) 은 값의 실제 타입을 돌려주는 함수다. 컴파일러가 추론한 타입을 눈으로 보려고 print 에 같이 넘겼다. Void 는 빈 튜플 () 의 다른 이름이라서 TaskGroup<()> 로 찍힌다. @main 은 이 구조체의 main() 을 프로그램 시작점으로 삼는 표시다. result.sorted { $0.id < $1.id } 는 sorted(by:) 에 trailing closure 를 넘겨 id 순으로 정렬한다. 자식 task 는 끝나는 순서대로 결과를 돌려주므로, 출력을 고정하려고 정렬했다. messages.map(\.id) 의 \.id 는 key path 이고, map 이 배열의 각 Message 에서 id 만 꺼내 새 배열을 만든다.
세 경우가 모두 of: 없이 컴파일되고 아래 그림처럼 정해졌다. 첫 번째는 자식이 Message, body 가 Array<Message> 다. 두 번째는 자식이 (), body 가 Int 다. 세 번째는 group.addTask {} 가 자식을 () 로, body 가 값을 돌려주지 않아서 GroupResult 도 () 로 정해진다.
![첫 addTask 가 돌려주는 타입이 TaskGroup 의 ChildTaskResult 가 되고, body 가 돌려주는 값의 타입이 GroupResult 가 되는 모습. 세 경우는 Message 와 Array
Void 자식 결과
피치에서 가장 길게 오간 것이 Void 자식이다. ktoso 가 처음 시험해 보고 쓴 글(#2)은 이렇다. group.addTask {} 는 ChildTaskResult 를 추론하지 못하고 group.addTask { () } 는 TaskGroup<Void> 로 추론이 된다. 그래서 Void 만을 위한 overload 를 하나 더 만드는 방법은 원치 않는다는 것이다. rlziii 는 withTaskGroup2 라는 감싸는 함수를 만들어 시험했더니 addTask { } 도 컴파일됐다고 답했고(#6), Void 경우가 입문자에게 가장 중요하다고 썼다. ktoso 는 최신 컴파일러에서는 Void 도 된다고 정정했다(#8). 오류 문구를 Xcode 빌드에서 복사했으니 옛 컴파일러였던 것 같다며, 더 확인해 보겠다고 했다.
6.4 에서 네 가지 모양을 다 돌려 봤다 (VoidCases.swift).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func emptyBody() async {
await withTaskGroup { group in
group.addTask {}
}
}
func unitBody() async {
await withTaskGroup { group in
group.addTask { () }
}
}
func stringBody() async {
await withTaskGroup { group in
group.addTask { "" }
}
}
func printBody() async {
await withTaskGroup { group in
group.addTask { print("hello") }
}
}
네 함수 모두 진단 0 개다. 정해진 타입은 type(of:) 로 찍어서 확인했다. unitBody, stringBody, printBody 의 모양을 VoidTypes.swift 에서 print 와 함께 실행한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@main
struct App {
static func main() async {
await withTaskGroup { group in
group.addTask { () }
print("unit:", type(of: group))
}
await withTaskGroup { group in
group.addTask { "" }
print("string:", type(of: group))
}
await withTaskGroup { group in
group.addTask { print("hello") }
print("print:", type(of: group))
}
}
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Common.swift VoidTypes.swift -o voidtypes
./voidtypes
1
2
3
4
unit: TaskGroup<()>
string: TaskGroup<String>
print: TaskGroup<()>
hello
{ () } 는 TaskGroup<()>, { "" } 는 TaskGroup<String>, { print("hello") } 는 print 가 Void 를 돌려주므로 TaskGroup<()> 다. hello 는 자식 task 가 실제로 돌았다는 표시다. emptyBody 의 addTask {} 는 앞에서 본 Kinds 의 세 번째 group 과 같은 모양이고, 그쪽에서 TaskGroup<()> 로 찍혔다. ktoso 가 처음에 겪은 addTask {} 의 막힘은 6.4 에서는 나오지 않는다. 그래서 Void 전용 overload 는 필요 없었다.
추론이 정해지는 자리
제안서 Detailed design 은 추론이 막히는 곳을 하나 짚는다. 타입 추론은 closure 본문을 위에서 아래로 보면서 진행하므로, group 을 처음 쓰는 문장이 addTask 가 아니면 ChildTaskResult 를 정할 근거가 없다는 것이다. 6.4 에서 어디가 근거가 되고 어디가 아닌지 하나씩 돌려 봤다.
CancelFirst.swift 는 제안서 예제처럼 group.cancelAll() 로 시작한다.
1
2
3
4
5
6
7
8
9
func cancelFirst(ids: [Int]) async {
await withTaskGroup { group in
group.cancelAll()
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
CancelFirst.swift:2:9: error: generic parameter 'ChildTaskResult' could not be inferred
1 | func cancelFirst(ids: [Int]) async {
2 | await withTaskGroup { group in
| `- error: generic parameter 'ChildTaskResult' could not be inferred
3 | group.cancelAll()
4 |
_Concurrency.withTaskGroup:3:24: note: in call to function 'withTaskGroup(of:returning:isolation:body:)'
1 | @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
2 | @backDeployed(before: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0)
3 | @inlinable public func withTaskGroup<ChildTaskResult, GroupResult>(of childTaskResultType: ChildTaskResult.Type = ChildTaskResult.self, returning returnType: GroupResult.Type = GroupResult.self, isolation: isolated (any Actor)? = #isolation, body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult) async -> GroupResult where ChildTaskResult : Sendable
| `- note: in call to function 'withTaskGroup(of:returning:isolation:body:)'
error 는 closure 안의 cancelAll() 이 아니라 withTaskGroup 호출 위치(2:9)에 붙는다. 컴파일러가 못 찾은 것이 withTaskGroup 의 generic 매개변수라서다. note 는 6.4 SDK 선언을 그대로 보여 준다. 고치는 방법은 제안서가 적은 대로 of: 를 되살리는 것이다(CancelFirstFixed.swift).
1
2
3
4
5
6
7
8
9
func cancelFirstFixed(ids: [Int]) async {
await withTaskGroup(of: Void.self) { group in
group.cancelAll()
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
}
}
진단은 0 개다. 막히는 첫 문장이 cancelAll() 만은 아니다. IsCancelledFirst.swift 는 group.isCancelled 를 먼저 읽는다. 리뷰에서 rnro 가 아쉬워한 바로 그 경우다(리뷰 #18, 아래).
1
2
3
4
5
6
7
8
9
func isCancelledFirst(ids: [Int]) async {
await withTaskGroup { group in
if group.isCancelled { return }
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
}
}
error 는 같은 문구가 2:9 에 붙는다.
1
IsCancelledFirst.swift:2:9: error: generic parameter 'ChildTaskResult' could not be inferred
(뒤따르는 소스 발췌와 note 는 CancelFirst 와 같아서 첫 줄만 옮긴다.) NextFirst.swift 는 group.next() 로 먼저 비우는 모양이다.
1
2
3
4
5
6
func nextFirst() async {
await withTaskGroup { group in
while let _ = await group.next() {}
group.addTask { await downloadMessage(for: 1) }
}
}
1
NextFirst.swift:2:9: error: generic parameter 'ChildTaskResult' could not be inferred
이 예제에서는 addTask { await downloadMessage(for: 1) } 가 뒤에서 Message 를 돌려주는데도 막힌다. next() 가 앞에 있으면 거기서 ChildTaskResult 를 모르는 채로 Optional<ChildTaskResult> 를 쓰게 되기 때문이다. 뒤의 addTask 가 앞의 next() 를 도와주지 못한다는 것이 “위에서 아래로” 의 뜻이다.
반대로 group 을 쓰는 문장이 먼저 있어도 막히지 않는 경우가 있다. DeferFirst.swift 는 defer 안에서 cancelAll() 을 부른다.
1
2
3
4
5
6
7
8
9
func deferFirst(ids: [Int]) async {
await withTaskGroup { group in
defer { group.cancelAll() }
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
}
}
진단 0 개다. 문장 순서로는 defer 가 addTask 보다 앞에 있는데도 ChildTaskResult 가 정해진다. 이유는 -dump-parse 로 파서가 만든 구문 트리를 보면 나온다.
1
xcrun swiftc -dump-parse DeferFirst.swift
1
2
(defer_stmt range=[DeferFirst.swift:3:5 - line:3:31]
(func_decl decl_context=0x7a50e379d8 implicit range=[DeferFirst.swift:3:5 - line:3:31] "$defer()" result="()" thrown_type="<null>"
(출력에서 defer 와 $defer 가 든 두 줄만 옮겼다.) defer 는 파서 단계에서 $defer() 라는 암시적(implicit) local 함수가 되고, cancelAll() 은 그 함수의 본문 안에 들어간다. closure 본문의 문장으로 group 을 쓰는 것이 아니라서 첫 사용으로 세지 않는다. 직접 만든 local 함수도 같다(LocalFuncFirst.swift).
1
2
3
4
5
6
7
8
9
func localFuncFirst(ids: [Int]) async {
await withTaskGroup { group in
func stop() { group.cancelAll() }
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
stop()
}
}
이 파일도 진단 0 개다. addTask 앞에 있는 local 함수 stop() 이 group.cancelAll() 을 쓰지만 ChildTaskResult 는 뒤의 addTask 에서 정해진다. 피치에서 wadetregaskis 가 Signal 앱이 defer 안에서 cancelAll 을 먼저 쓴다며 이 경우를 물었고(#18), ktoso 는 지금처럼 타입을 명시한 spelling 을 유지해야 할 것이라고 예상했다(#19). 6.4 측정은 그 예상과 대비된다. defer 안의 cancelAll() 은 of: 없이 빌드된다.
group 을 쓰지 않는 문장은 얼마든지 앞에 와도 된다(OtherFirst.swift).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func otherFirst(ids: [Int]) async -> Int {
await withTaskGroup { group in
let count = ids.count
print("adding \(count) tasks")
for id in ids {
group.addTask { await downloadMessage(for: id) }
}
return count
}
}
func unlessCancelledFirst(ids: [Int]) async {
await withTaskGroup { group in
for id in ids {
_ = group.addTaskUnlessCancelled { await downloadMessage(for: id) }
}
}
}
두 함수 모두 진단 0 개다. 기준은 “closure 의 첫 문장” 이 아니라 “group 을 쓰는 첫 자리” 이고, 그 자리가 addTask 든 addTaskUnlessCancelled 든 근거가 된다.
결과를 표로 모으면 이렇다.
| group 을 쓰는 첫 자리 | 결과 |
|---|---|
group.addTask { ... } | 추론된다 |
group.addTaskUnlessCancelled { ... } | 추론된다 |
group.cancelAll() | ChildTaskResult could not be inferred |
if group.isCancelled { return } | ChildTaskResult could not be inferred |
while let _ = await group.next() {} | ChildTaskResult could not be inferred |
defer { group.cancelAll() } 다음에 addTask | 추론된다 |
group 을 안 쓰는 문장 다음에 addTask | 추론된다 |
피치에서 이 한계를 처음 짚은 것은 xedin 이다. ktoso 가 전한 그의 경고는 두 가지다(#17). 하나는 group 이 overload 된 함수의 인자로 자주 넘어가면 타입 검사 성능이 나빠질 수 있다는 것이다. 다른 하나는 group 을 쓰는 첫 표현식이 타입을 정하므로 cancelAll 과 addTask 의 순서에 따라 컴파일이 되기도 하고 안 되기도 한다는 것이다. ktoso 는 group 에 addTask 전에 다른 일을 하는 일이 흔하지 않아서 사소한 걱정이라 보았고, 그래서 이 개선을 진행하자고 했다. 리뷰에서 rnro 는 group.isCancelled 를 먼저 보고 싶은 사람이 있을 수 있어서 아쉽지만, 컴파일 시간을 지켜 준다면 escape hatch(of:) 가 있으니 타협할 만하다고 썼다(리뷰 #18). Paul_Cantrell 은 이런 모서리 경우가 Swift 타입 추론 일반과 같은 성격이라서 이 제안을 막을 이유가 아니라고 했고, 대응은 오류 메시지와 도구를 계속 다듬는 것이라고 썼다(리뷰 #4).
자식 결과 타입이 어긋날 때
ChildTaskResult 를 첫 addTask 가 정하면, 같은 group 의 다음 addTask 가 다른 타입을 돌려줄 때 어떻게 되는지 본다. 먼저 Message 를 돌려주는 addTask 다음에 Void 를 돌려주는 addTask 를 둔 경우다(Mismatch.swift).
1
2
3
4
5
6
func mismatch(id: Int) async {
await withTaskGroup { group in
group.addTask { await downloadMessage(for: id) }
group.addTask { await logMessageReceived(for: id) }
}
}
1
2
3
4
5
6
7
Mismatch.swift:4:21: error: cannot convert value of type '()' to closure result type 'Message'
2 | await withTaskGroup { group in
3 | group.addTask { await downloadMessage(for: id) }
4 | group.addTask { await logMessageReceived(for: id) }
| `- error: cannot convert value of type '()' to closure result type 'Message'
5 | }
6 | }
첫 addTask 가 Message 로 정했으니 둘째가 틀렸다고 나온다. error 가 틀린 쪽(둘째 줄)에 붙어서 읽기 쉽다. 피치에서 jim 이 걱정한 것, 곧 “맨 위에 기준이 되는 타입이 없으면 오류가 더 헷갈리지 않느냐” 에 대한 답이 이 모양이다(#3). ktoso 는 자기 예제("" 다음에 12)에서 나온 Cannot convert value of type 'Int' to closure result type 'String' 을 들어 답했고, 원하면 withTaskGroup(of: String.self) 처럼 적을 수 있다고 덧붙였다(#4). 이 글의 6.4 측정에서도 오류는 같은 형태다.
순서를 바꾸면 이야기가 달라진다. Void 를 돌려주는 addTask 를 먼저 두고 Message 를 돌려주는 것을 나중에 두었다(MismatchReverse.swift).
1
2
3
4
5
6
func mismatchReverse(id: Int) async {
await withTaskGroup { group in
group.addTask { await logMessageReceived(for: id) }
group.addTask { await downloadMessage(for: id) }
}
}
1
2
3
4
5
6
7
8
9
MismatchReverse.swift:4:27: warning: result of call to 'downloadMessage(for:)' is unused [#NoUsage]
2 | await withTaskGroup { group in
3 | group.addTask { await logMessageReceived(for: id) }
4 | group.addTask { await downloadMessage(for: id) }
| `- warning: result of call to 'downloadMessage(for:)' is unused [#NoUsage]
5 | }
6 | }
[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>
error 가 아니라 warning 하나이고, 진단 대상은 downloadMessage 의 결과가 쓰이지 않는다는 것이다. 첫 addTask 가 ChildTaskResult 를 Void 로 정한 뒤, 둘째 addTask 의 { await downloadMessage(for: id) } 는 Void 를 돌려주는 closure 로 해석된다. 한 표현식으로만 이루어진 closure 는 기대한 결과 타입이 Void 면 그 표현식의 값을 버려도 된다는 규칙이 있어서다. 그래서 Message 가 아무도 모르게 버려진다. 순서만 바꿨을 뿐인데 error 가 warning 으로 바뀌고 결과가 사라지는 것이 이 글에서 가장 쓸모 있는 함정이다. 위쪽의 error 는 Message 가 먼저 정해져서 Void 가 거부당한 것이고, 아래쪽은 Void 가 먼저 정해져서 Message 가 버려진 것이다.
명시한 경우도 같은 규칙을 탄다. 제안서 Detailed design 의 마지막 예제가 이 모양이다. of: Void.self 를 적고 Message 를 돌려주는 단일 표현식 closure 를 넣었다(MismatchExplicit.swift).
1
2
3
4
5
6
func mismatchExplicit(id: Int) async {
await withTaskGroup(of: Void.self) { group in
group.addTask { await downloadMessage(for: id) }
group.addTask { await logMessageReceived(for: id) }
}
}
1
2
3
4
5
6
7
8
9
MismatchExplicit.swift:3:27: warning: result of call to 'downloadMessage(for:)' is unused [#NoUsage]
1 | func mismatchExplicit(id: Int) async {
2 | await withTaskGroup(of: Void.self) { group in
3 | group.addTask { await downloadMessage(for: id) }
| `- warning: result of call to 'downloadMessage(for:)' is unused [#NoUsage]
4 | group.addTask { await logMessageReceived(for: id) }
5 | }
[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>
제안서의 코드 주석에는 이 자리에서 cannot convert value of type 'Message' to closure result type 'Void' 가 난다고 적혀 있다. 6.4 에서 MismatchExplicit.swift 는 warning 하나로 컴파일되고, 그 문구의 error 는 return 을 적은 MismatchReturn.swift 에서 나온다. 같은 규칙으로 Void 로 정해진 뒤의 단일 표현식 closure 는 결과를 버린다.
갈리는 지점은 문장이 여러 개인지가 아니라 return 을 적었는지다. 먼저 여러 문장에 return 이 있는 경우다(MismatchReturn.swift).
1
2
3
4
5
6
7
8
9
func mismatchReturn(id: Int) async {
await withTaskGroup(of: Void.self) { group in
group.addTask {
let message = await downloadMessage(for: id)
return message
}
group.addTask { await logMessageReceived(for: id) }
}
}
1
2
3
4
5
6
7
MismatchReturn.swift:5:14: error: cannot convert value of type 'Message' to closure result type 'Void'
3 | group.addTask {
4 | let message = await downloadMessage(for: id)
5 | return message
| `- error: cannot convert value of type 'Message' to closure result type 'Void'
6 | }
7 | group.addTask { await logMessageReceived(for: id) }
한 줄이어도 return 을 적으면 같다. 이번에는 of: 없이 Void 가 먼저 정해진 group 이다(ExplicitReturnSingle.swift).
1
2
3
4
5
6
func explicitReturnSingle(id: Int) async {
await withTaskGroup { group in
group.addTask { await logMessageReceived(for: id) }
group.addTask { return await downloadMessage(for: id) }
}
}
1
2
3
4
5
6
7
ExplicitReturnSingle.swift:4:28: error: cannot convert value of type 'Message' to closure result type '()'
2 | await withTaskGroup { group in
3 | group.addTask { await logMessageReceived(for: id) }
4 | group.addTask { return await downloadMessage(for: id) }
| `- error: cannot convert value of type 'Message' to closure result type '()'
5 | }
6 | }
{ return await downloadMessage(for: id) } 는 4:28 에서 error 가 난다. 단일 표현식이라도 return 이 있으면 값을 버리는 규칙이 적용되지 않는다. MismatchReverse 에서는 return 이 없어서 warning 이었던 바로 그 closure 다.
반대로 of: Message.self 처럼 실제 결과 타입을 적어 두면 Void 를 돌려주는 쪽이 error 로 드러난다(OfMessage.swift).
1
2
3
4
5
6
func ofMessage(id: Int) async {
await withTaskGroup(of: Message.self) { group in
group.addTask { await logMessageReceived(for: id) }
group.addTask { await downloadMessage(for: id) }
}
}
1
2
3
4
5
6
7
OfMessage.swift:3:21: error: cannot convert value of type '()' to closure result type 'Message'
1 | func ofMessage(id: Int) async {
2 | await withTaskGroup(of: Message.self) { group in
3 | group.addTask { await logMessageReceived(for: id) }
| `- error: cannot convert value of type '()' to closure result type 'Message'
4 | group.addTask { await downloadMessage(for: id) }
5 | }
정리하면 명시하든 추론하든 기준은 “먼저 정해진 타입” 이고, return 이 없는 단일 표현식 closure 는 그 타입이 Void 일 때 값을 버리는 쪽으로 맞춰진다. 자식 결과를 쓰는 group 에서는 of: Message.self 처럼 실제 결과 타입을 적어 두는 편이 안전하다.
group 을 다른 함수에 넘길 때
“group 을 쓰는 첫 자리” 가 group 을 다른 함수에 넘기는 호출일 수도 있다. 그 함수가 overload 라서 여러 타입을 받을 수 있으면 어떻게 될까. 피치에서 xedin 이 걱정한 “overload 된 인자” 가 이 모양이다. Overload.swift 는 TaskGroup<Int> 와 TaskGroup<String> 을 받는 fill 을 둘 만들어서 첫 문장에서 부른다.
1
2
3
4
5
6
7
8
func fill(_ group: inout TaskGroup<Int>) { group.addTask { 1 } }
func fill(_ group: inout TaskGroup<String>) { group.addTask { "a" } }
func passFirst() async {
await withTaskGroup { group in
fill(&group)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
Overload.swift:6:5: error: ambiguous use of 'fill'
1 | func fill(_ group: inout TaskGroup<Int>) { group.addTask { 1 } }
| `- note: found this candidate
2 | func fill(_ group: inout TaskGroup<String>) { group.addTask { "a" } }
| `- note: found this candidate
3 |
4 | func passFirst() async {
5 | await withTaskGroup { group in
6 | fill(&group)
| `- error: ambiguous use of 'fill'
7 | }
8 | }
TaskGroup<Int> 인지 TaskGroup<String> 인지 group 으로는 정할 수 없어서 fill 의 어느 쪽인지도 정하지 못한다. 이번 error 는 withTaskGroup 이 아니라 fill 의 호출(6:5)에 붙는다. overload 가 하나뿐이면 group 을 넘기는 것이 근거가 된다(OverloadOne.swift).
1
2
3
4
5
6
7
8
9
10
func fillOne(_ group: inout TaskGroup<Int>) { group.addTask { 1 } }
func passFirstOne() async -> Int {
await withTaskGroup { group in
fillOne(&group)
var sum = 0
for await n in group { sum += n }
return sum
}
}
진단은 0 개다. fillOne 의 매개변수 타입이 TaskGroup<Int> 하나이므로 ChildTaskResult 는 Int 로 정해진다. group 을 다른 함수에 넘기는 자리도 근거가 될 수 있지만, 그 함수의 매개변수 타입이 하나로 정해질 때만이다.
Sendable 제약
ChildTaskResult : Sendable 제약은 추론으로 바뀌지 않는다. Sendable 이 아닌 클래스 NonSendable 을 돌려주는 addTask 를 추론으로 써 봤다(NonSendableChild.swift). NonSendable 은 final class NonSendable { var value = 0 } 로 Common.swift 에 있다.
1
2
3
4
5
func nonSendableChild() async {
await withTaskGroup { group in
group.addTask { NonSendable() }
}
}
Swift 6 모드에서는 error 가 셋이다. 위치는 2:9, 2:23, 3:11 이다. 앞의 둘만 옮긴다.
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
NonSendableChild.swift:2:9: error: type 'NonSendable' does not conform to the 'Sendable' protocol
1 | func nonSendableChild() async {
2 | await withTaskGroup { group in
| `- error: type 'NonSendable' does not conform to the 'Sendable' protocol
3 | group.addTask { NonSendable() }
4 | }
Common.swift:4:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 | func downloadMessage(for id: Int) async -> Message { Message(id: id) }
3 | func logMessageReceived(for id: Int) async {}
4 | final class NonSendable { var value = 0 }
| `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
5 |
NonSendableChild.swift:2:23: error: type 'NonSendable' does not conform to the 'Sendable' protocol
1 | func nonSendableChild() async {
2 | await withTaskGroup { group in
| `- error: type 'NonSendable' does not conform to the 'Sendable' protocol
3 | group.addTask { NonSendable() }
4 | }
Common.swift:4:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 | func downloadMessage(for id: Int) async -> Message { Message(id: id) }
3 | func logMessageReceived(for id: Int) async {}
4 | final class NonSendable { var value = 0 }
| `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
5 |
셋째(3:11)는 group.addTask 자리에 같은 문구로 붙는다. 이 error 는 추론이 ChildTaskResult 를 NonSendable 로 정한 뒤에 제약을 확인해서 나온 것이다. 명시해도 같다. of: NonSendable.self 로 적은 NonSendableExplicit.swift 는 위치만 2:9, 2:45, 3:11 로 다르고 문구와 note 는 같다.
1
2
3
4
5
func nonSendableExplicit() async {
await withTaskGroup(of: NonSendable.self) { group in
group.addTask { NonSendable() }
}
}
두 파일을 세 언어 모드로 돌린 결과는 이렇다.
| 모드 | NonSendableChild | NonSendableExplicit |
|---|---|---|
| Swift 5 | 0 개 | 0 개 |
| Swift 5 complete | warning 3 개 (this is an error in the Swift 6 language mode 가 붙는다) | warning 3 개 |
| Swift 6 | error 3 개 | error 3 개 |
of: 를 쓰든 안 쓰든 제약이 걸리는 모드와 정도가 같다. 추론은 Sendable 제약을 피하는 길이 아니다.
throwing 과 discarding
withThrowingTaskGroup 도 같은 방식으로 추론된다(Throwing.swift).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct DownloadError: Error {}
func fetch(_ id: Int) async throws -> Message {
if id < 0 { throw DownloadError() }
return Message(id: id)
}
func throwingInferred(ids: [Int]) async throws -> [Message] {
try await withThrowingTaskGroup { group in
for id in ids {
group.addTask { try await fetch(id) }
}
var result: [Message] = []
for try await m in group { result.append(m) }
return result
}
}
func discarding(ids: [Int]) async {
await withDiscardingTaskGroup { group in
for id in ids {
group.addTask { await logMessageReceived(for: id) }
}
}
}
두 함수 모두 진단 0 개다. fetch 가 throws 라서 자식 closure 도 던질 수 있고, for try await 가 error 를 받는다. ChildTaskResult 는 Message 로 정해진다. withDiscardingTaskGroup 은 ChildTaskResult 매개변수 자체가 없어서 이 제안의 영향이 없다.
컴파일 시간
type 추론은 늘어날수록 컴파일 시간이 걱정된다. 피치에서 vns 가 +1 을 하면서 이 점을 짚었고(#10), 별개로 non-escapable 타입이 생겨 API 전체가 나아질 때까지 기다리는 편이 낫겠다는 의견도 냈다. 리뷰에서 ktoso 는 xedin 과 확인했고 컴파일 시간이 크게 늘 걱정은 없다고 썼다(리뷰 #7). vns 는 그것이 중요한 걱정이었다며 +1 을 했다(리뷰 #8).
이 글에서도 직접 재 봤다. gen_timing.sh 200 으로 같은 모양의 함수 200 개를 of: Message.self 를 적은 판(TimingExplicit.swift)과 뺀 판(TimingInferred.swift)으로 만들었다. 각 함수는 addTask, for await, filter, map 이 든 task group 하나다. 추론판의 첫 함수는 이렇다.
1
2
3
4
5
6
7
8
9
10
11
12
func f1(ids: [Int]) async -> [Int] {
await withTaskGroup { group in
for id in ids {
group.addTask { await downloadMessage(for: id + 1) }
}
var result: [Int] = []
for await message in group {
result.append(message.id * 2 + 1)
}
return result.filter { $0 > 1 }.map { $0 - 1 }
}
}
filter 와 map 으로 배열 가공하기
filter { $0 > 1 } 은 조건이 참인 원소만 남긴 새 배열을 만들고, map { $0 - 1 } 은 각 원소를 변환한 새 배열을 만든다. 둘을 이어 붙이면 body 의 return 식에 타입 검사 일거리가 조금 더 생긴다. 타입 추론 비용을 재려는 모양에 일부러 넣었다.
두 파일은 2400 줄씩이고, 명시판은 withTaskGroup(of: Message.self) 만 다르다. /usr/bin/time -p 로 -emit-sil 을 다섯 번씩 돌렸다.
1
/usr/bin/time -p xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift TimingInferred.swift
| 판 | 실행 시간 (초) | 범위 |
|---|---|---|
명시 (of: Message.self) | 1.04, 1.08, 1.03, 1.03, 1.11 | 1.03 ~ 1.11 |
| 추론 | 1.13, 1.03, 1.03, 1.18, 1.19 | 1.03 ~ 1.19 |
범위가 겹치고 차이는 측정 오차 안에 있다. 이 정도 규모의 같은 모양 함수에서는 추론판이 느리다는 신호가 없다. 이 숫자는 그 모양과 규모에 대한 것이다.
배포 대상 OS
기본 인자는 호출하는 쪽에서 채워 넣는 값이라서 런타임 함수는 바뀌지 않는다. 그래서 제안서의 Implications on adoption 은 배포 제약이 없다고 쓴다. 타깃을 낮춰서 돌려 봤다.
1
2
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Motivation.swift -target arm64-apple-macos13
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Kinds.swift -target arm64-apple-macos10.15
Motivation.swift 는 macOS 13 으로, Kinds.swift 는 macOS 10.15 로 낮춰도 둘 다 진단 0 개다. withTaskGroup 은 macOS 10.15 부터 있는 함수이고, 이 제안이 호출 쪽 소스만 바꾸기 때문이다.
앞에서 본 @backDeployed(before: macOS 15.0, ...) 는 이 제안 때문에 붙은 것이 아니다. isolation: 매개변수가 macOS 15 에서 더해졌기 때문이다. SE-0420 글에서 다룬 것이고, 옛 OS 에서는 앱에 복사된 본문이 대신 돈다. 한편 withDiscardingTaskGroup 은 @available(macOS 14.0, ...) 라서 Throwing.swift 를 -target arm64-apple-macos10.15 로 돌리면 discarding 함수의 두 곳에서 error 가 나온다. 19:9 의 withDiscardingTaskGroup(returning:isolation:body:) 와 21:13 의 addTask(priority:operation:) 이고, 둘 다 is only available in macOS 14.0 or newer 다. 이것은 SE-0381 이 둔 제약이고 withThrowingTaskGroup 쪽에는 진단이 없다.
기대 효과
- 흔한 경우의
of:가 사라진다.for문으로addTask를 부르는 가장 일반적인 모양은withTaskGroup { group in만으로 쓸 수 있다. 위inferred와explicit은 한 줄 차이이고, 읽는 사람은of: Message.self가 무엇인지 따로 알 필요가 없다. - 입문하는 사람이 덜 헷갈린다. 리뷰에서 jim 은 처음
withTaskGroup을 썼을 때 왜 타입을 적어야 하는지 혼란스러웠다고 했다(리뷰 #10). 제안서도ChildTaskResult와GroupResult의 차이를 이해하기 혼란스럽다는 점을 동기로 든다. 특히 한쪽 또는 둘이Void일 때가 그렇다. returning:과 모양이 맞는다. 두 매개변수 모두 기본값이 있고, 둘 다 호출하는 쪽 문맥에서 정해진다.- 소스와 ABI 가 호환된다.
of:를 생략하는 것은 새로 생긴 방법이라서 기존 코드는 그대로 컴파일되고, 기본 인자를 더하는 것은 바이너리 호환 변경이다.
다른 선택지는 왜 안 됐나
제안서의 Alternatives considered 는 한 줄이다. 주된 대안은 아무것도 하지 않는 것이다. 나머지는 스레드에서 나온 것들이다.
그대로 두기
of: 를 계속 필수로 두는 대안이다. 이쪽의 근거는 추론이 늘면 오류 메시지가 나빠지고 컴파일 시간이 늘 수 있다는 걱정이었다. 피치에서 wadetregaskis 는 지금도 closure 서명 오류가 이해하기 어려운데 추론을 더하면 더 나빠질까 걱정했다(#9). 앞에서 본 오류들은 error 위치가 틀린 addTask 나 withTaskGroup 호출에 붙고 문구가 could not be inferred, cannot convert value of type 처럼 이름을 짚어 준다. 컴파일 시간도 측정에서 차이가 없었고, 리뷰에서 ktoso 가 xedin 과 확인한 내용과 같다(리뷰 #7). 다만 예외가 하나 있다. Void 가 먼저 정해진 group 에서 return 없이 값을 돌려주는 단일 표현식 closure 는 error 없이 warning 만 남고 결과가 버려진다(MismatchReverse.swift). of: Message.self 처럼 결과 타입을 적어 두면 이 경우도 error 로 드러난다(OfMessage.swift). LSG 는 이 제안을 제안서 그대로 수락했다.
Void 전용 overload
addTask {} 가 추론되지 않는다고 본 ktoso 는 Void 전용 overload 를 더할 수도 있었지만, 이미 overload 가 여럿이라 원치 않는다고 썼다(#2). 6.4 측정에서 addTask {} 도 추론되므로 overload 없이 해결됐다.
metatype 기본 인자를 표준 라이브러리 전체로
리뷰에서 Quedlinbug 는 두 가지를 요구했다. 매개변수 이름 childTaskResultType 과 returnType 을 _ 로 바꾸자는 것이었고(리뷰 #6), 이 .self 기본값이 어울리지 않는 API 의 예가 없다면 표준 라이브러리 전체로 일반화하자는 것이었다. 앞의 것에 rlziii 는 두 이름이 withTaskGroup 과 withThrowingTaskGroup 의 함수 구현 안에서 쓰여서 _ 로 바꿀 수 없다고 답했다(리뷰 #9). Quedlinbug 는 쓰이는 곳을 찾지 못했다며, argumentLabel _ 를 문서화할 수 없는 버그도 이 제안과 같이 고치자고 했다(리뷰 #11). xwu 는 이 제안과 상관없으니 다른 스레드에서 하자고 했다(리뷰 #12).
일반화 쪽에서 Quedlinbug 가 든 metatype 기본값의 세 패턴(리뷰 #11)을 6.4 에서 돌렸다(Metatype.swift).
1
2
3
4
5
6
7
8
9
func concreteDefault<T>(_: T.Type = String.self) {}
func genericDefault<T>(_: T.Type = T.self) {}
func genericReturn<T>(_: T.Type = T.self) -> T.Type { T.self }
func use() {
concreteDefault()
let _ = genericReturn() as String.Type
genericDefault()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
Metatype.swift:8:3: error: generic parameter 'T' could not be inferred
1 | func concreteDefault<T>(_: T.Type = String.self) {}
2 | func genericDefault<T>(_: T.Type = T.self) {}
| `- note: in call to function 'genericDefault'
3 | func genericReturn<T>(_: T.Type = T.self) -> T.Type { T.self }
4 |
:
6 | concreteDefault()
7 | let _ = genericReturn() as String.Type
8 | genericDefault()
| `- error: generic parameter 'T' could not be inferred
9 | }
10 |
concreteDefault() 는 String.self 가 정해져 있어서 문제없고, genericReturn() as String.Type 은 반환 타입이 근거라서 통과한다. genericDefault() 는 T 를 정할 근거가 없어서 error 다. 세 패턴 가운데 둘은 통과하고 하나는 막힌다.
이 일반화에 Douglas_Gregor 가 반례를 들었다. unsafeBitCast(_:to:) 다. 초기의 Swift 에서 일부러 to 인자를 호출 자리에 쓰게 만든 것이라고 했다. 추론으로 알아낼 수 있어도 어떤 변환인지 호출 자리에서 명백하게 보이도록 한 설계다(리뷰 #20). BitCast.swift 로 측정했다.
1
2
3
4
5
6
func bits(_ x: Float) -> UInt32 {
unsafeBitCast(x, to: UInt32.self)
}
func bitsInferred(_ x: Float) -> UInt32 {
unsafeBitCast(x)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
BitCast.swift:2:3: warning: 'unsafeBitCast' from 'Float' to 'UInt32' can be replaced with 'bitPattern' property on 'Float'
1 | func bits(_ x: Float) -> UInt32 {
2 | unsafeBitCast(x, to: UInt32.self)
| `- warning: 'unsafeBitCast' from 'Float' to 'UInt32' can be replaced with 'bitPattern' property on 'Float'
3 | }
4 | func bitsInferred(_ x: Float) -> UInt32 {
BitCast.swift:5:18: error: missing argument for parameter 'to' in call
3 | }
4 | func bitsInferred(_ x: Float) -> UInt32 {
5 | unsafeBitCast(x)
| `- error: missing argument for parameter 'to' in call
6 | }
7 |
Swift.unsafeBitCast:1:24: note: 'unsafeBitCast(_:to:)' declared here
1 | @inlinable public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U
| `- note: 'unsafeBitCast(_:to:)' declared here
unsafeBitCast 로 비트를 그대로 다른 타입으로 읽기
unsafeBitCast(_:to:) 은 값의 비트를 바꾸지 않고 다른 타입으로 해석하는 함수다. 선언을 보면 to type: U.Type 에 기본값이 없어서, unsafeBitCast(x) 는 to 가 빠졌다는 error 가 난다. 반환 타입이 UInt32 로 정해져 있어도 그렇다. Douglas_Gregor 의 설명대로 어떤 변환인지 호출 자리에서 보이게 하려고 타입을 일부러 쓰게 한 것이다. 첫 warning 은 Float 에서 UInt32 로는 bitPattern 프로퍼티를 쓰라는 안내다.
수락 공지(Douglas_Gregor)는 이 문제를 이렇게 정리했다. 리뷰 반응은 압도적으로 긍정이었다. 비슷한 API 에도 같은 기본값을 줄 수 있다는 의견이 나왔지만, LSG 는 그런 일반화는 이 제안의 범위 밖이고 별도 제안으로 다룰 수 있다고 보았다.
앞으로의 방향
이 제안과 별개로 이야기된 방향이 둘 있다. 하나는 제안서 Future directions 에 있고, 하나는 스레드에서 ktoso 가 꺼낸 것이다.
with 없는 TaskGroup API
제안서 Future directions 는 with... closure 없이 쓰는 task group 을 상상한다. group 이 scope 를 벗어나면 자동으로 waitForAll() 이 되는 모양이다.
1
2
3
4
5
6
7
// Potential long-term direction that might be possible:
func test() async {
let group = TaskGroup<Int>()
group.addTask { /* ... */ }
// Going out of scope would have to imply `group.waitForAll()`...
}
이렇게 되면 추론 규칙이 달라지고 group 은 컬렉션처럼 TaskGroup<Int> 로 만들 것이라고 제안서는 쓴다. 피치에서 이 이야기는 ktoso 의 ~Escapable 구상에서 나왔다. group 이 scope 밖으로 나가지 못하게 하는 타입이면 with 가 필요 없을 수도 있다는 것이었다(#4). xwu 는 그렇다면 TaskGroup(of: Int.self) 보다 TaskGroup<Int>() 가 자연스럽지 않으냐고 물었고(#12), ktoso 는 맞는 지적이라고 답했다(#13). dnadoba 는 그 모양이 안 되는 이유를 짚었다(#14). with[Throwing]TaskGroup 은 모든 자식 task 가 끝나기를 기다리고, closure 에서 error 가 던져지면 자식을 모두 취소한다. 그런데 ~Escapable 이나 ~Copyable 은 지금 제안된 모양으로는 비동기 정리(cleanup)나 error 를 “받는” 일을 못 한다는 것이다. ktoso 도 이것은 이상으로 둔 방향이지 지금 제안이 아니라고 했고, 비동기 정리를 위한 “resource scope” 같은 것이 필요하다고 인정했다(#15). 제안서는 이 제안이 그 방향을 막지 않는다고 쓴다.
Throwing 과 non-throwing 합치기
ktoso 는 typed throws 로 ThrowingTaskGroup 과 TaskGroup 을 하나로 합치는 계획도 언급했다(피치 #13). 그러면 TaskGroup<Int, Never>() 와 TaskGroup<Int, Error>() 가 되고, discarding group 은 따로 남아서 독립된 타입 네 개가 둘로 줄어든다는 것이다. 이 작업은 “Typed throws in the Concurrency module” 제안이 6.0 에서 미뤄진 이유이기도 하다고 그는 썼다. 리뷰에서도 ktoso 는 이 제안이 Throwing 버전을 합치는 작업을 막지 않는다고 썼다(리뷰 #7). Quedlinbug 는 자기가 만든, withThrowingTaskGroup 을 감싼 typed throws overload 에서 순회할 때 error 를 as! 로 변환하지 않아도 되는지 물었다(#21). typed throws 는 SE-0413 이 도입했다.
마이그레이션
할 일이 없다. 기존의 of: Message.self 는 그대로 컴파일되고, 지우는 것은 선택이다.
of: 를 지울 때만 살펴볼 곳이 셋이다.
- group 을 쓰는 첫 자리가
addTask가 아닌 함수.cancelAll,isCancelled,next()가 먼저 나오면could not be inferred가 난다.defer안의cancelAll은 통과한다. - 자식 결과 타입이 섞인 함수.
Message를 돌려주는addTask가Void보다 앞이면 error 로 나오지만,Void가 앞이면Message를 돌려주는 단일 표현식 closure 의 결과가 버려지고result of call ... is unusedwarning 만 남는다. - 결과를 쓰는 group 을
Void로 착각하는 경우. 위 둘째와 같은 원인이다. 자식 결과를 모아 쓰는 코드라면 첫addTask가 실제로 값을 돌려주는지 확인한다.
정리
withTaskGroup과withThrowingTaskGroup의of:에= ChildTaskResult.self기본값이 더해져서, 흔한 task group 은of:없이 쓸 수 있다.GroupResult는 원래부터returning:의 기본값으로 추론됐다.- 6.4 에서
ChildTaskResult는 closure 본문을 위에서 아래로 보다가 group 을 쓰는 첫 자리에서 정해진다.addTask,addTaskUnlessCancelled, 그리고 타입이 하나로 정해진 함수에 group 을 넘기는 호출이 근거이고,cancelAll,isCancelled,next()가 먼저 오면generic parameter 'ChildTaskResult' could not be inferred다. group 을 안 쓰는 문장과defer본문, local 함수 본문은 건너뛴다. Void자식은addTask {},addTask { () },addTask { print(...) }모두TaskGroup<()>로 추론된다. 별도 overload 는 필요 없었다.- 자식 타입이 어긋나면 먼저 정해진 타입이 기준이다.
Message가 먼저면Void쪽이 error 이고,Void가 먼저면return없이Message를 돌려주는 단일 표현식 closure 의 결과가 조용히 버려진다.Sendable제약은 추론으로도 그대로 걸린다. - 컴파일 시간은 같은 모양 함수 200 개에서 차이가 오차 범위 안이었다. 호출 쪽 소스만 바뀌어서 macOS 10.15 타깃에서도 쓸 수 있다.
- 다른 metatype 기본 인자로의 일반화는 이 제안의 범위 밖이다.
unsafeBitCast(_:to:)처럼 일부러 호출 자리에 타입을 쓰게 한 API 도 있다. - 실제 프로젝트에서는
withTaskGroup(of: Void.self)로 쓰던 곳이 가장 눈에 띄게 줄어든다. 지울 때는 첫 사용이addTask인지, 자식 타입이 하나로 모이는지만 보면 된다.
관련 글
- [SE-0414] Region based Isolation
- [SE-0420] Inheritance of actor isolation
- [SE-0421] Generalize effect polymorphism for AsyncSequence and AsyncIteratorProtocol
- [SE-0430] sending parameter and result values
- [SE-0431] @isolated(any) Function Types
- [SE-0434] Usability of global-actor-isolated types
