[SE-0421] Generalize effect polymorphism for AsyncSequence and AsyncIteratorProtocol
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0421
- 상태: Implemented (Swift 6.0)
- upcoming feature flag: 없음 (6.0 표준 라이브러리에 새 requirement 가 들어오는 제안이라 켜고 끄는 flag 가 따로 없다)
- 저자: Doug Gregor, Holly Borla
- 리뷰 매니저: Freddy Kellison-Linn
- pitch: Pitch (2024-01-05)
- 리뷰: Review (2024-01-26 부터 02-07 까지)
- 수락: Accepted (2024-02-11)
- 전제 제안서: SE-0413: Typed throws, SE-0313: Improved control over actor isolation, SE-0414 (region based isolation), SE-0420 (
#isolation)
한 줄 요약
AsyncIteratorProtocol 에 “부른 쪽의 isolation 을 받고, 던지는 에러 타입을 Failure 로 드러내는” 새 requirement next(isolation:) 를 더했다. Element 와 Failure 는 primary associated type 이 되었고, for await 는 배포 대상이 macOS 15 이상이면 next() 대신 이 함수를 부른다.
어떤 문제였나
AsyncSequence 는 처음부터 두 가지에 대해 “다형적” 이려고 했다. 하나는 던지느냐 아니냐다. 어떤 시퀀스는 순회하다 에러를 던지고, 어떤 시퀀스는 절대 던지지 않는다. 던지는 시퀀스만 for try await 를 요구하고 안 던지는 시퀀스는 for await 로 충분해야 한다. 다른 하나는 actor isolation 이다. 어떤 actor 안에서 순회하든 원소를 안전하게 받아야 한다. 제안서는 이 두 의도가 현재 API 로는 “표현력, Sendable 검사, 실행 성능” 모두에서 한계에 부딪혔다고 쓴다.
이 글은 그 한계를 세 갈래로 나눠 하나씩 직접 재현한 뒤, 제안이 무엇을 바꾸는지 따라간다. 앞 글에서 다룬 개념은 짧게 짚고 링크로 넘긴다.
- SE-0414 글: non-Sendable 값을 같은 region 으로 묶어, 다른 isolation 으로 보내도 되는지 컴파일러가 판단하는 방식
- SE-0420 글: nonisolated
async함수가 부른 쪽 actor 를 떠나는 이유와#isolation - SE-0430 글: 값을 통째로 넘기는
sending
actor 안에서 도는 for await
제안서 Motivation 의 첫 예제는 이렇다. @MainActor 함수 안에서, 원소가 Sendable 이 아닌 AsyncStream 을 for await 로 돈다. 제안서 주석에는 이 줄에서 non-sendable type 'NotSendable?' returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary 경고가 난다고 적혀 있다. 이 글의 모든 예제는 Common.swift 의 클래스 하나를 같이 컴파일한다.
Common.swift
1
final class NonSendable { var value = 0 }
제안서의 예제를 이 클래스로 옮긴 것이 아래 코드다.
Motivation.swift
1
2
3
4
5
6
@MainActor
func iterate(over stream: AsyncStream<NonSendable>) async {
for await element in stream {
print(element.value)
}
}
AsyncStream 으로 값을 흘려 보내기
AsyncStream 은 값을 하나씩 만들어 내보내는 AsyncSequence 다. for await 로 값이 올 때마다 받는다. 위 코드는 AsyncStream<NonSendable> 을 인자로 받아서 도는 것뿐이라, 값을 만드는 쪽은 나오지 않는다. MainActor 는 main thread 에 묶인 global actor 로, @MainActor 를 붙인 함수는 그 actor 안에서 돈다.
이 코드를 Swift 6 언어 모드로 컴파일하면 어떤 진단이 나올까. 진단은 -typecheck 가 아니라 -emit-sil 로 본다. -emit-sil 은 SIL(Swift Intermediate Language) 까지 컴파일하라는 옵션이다. data race 검사 중 일부(region 분석이 하는 sending 검사 등)는 타입 검사 뒤 SIL 단계에서 돌기 때문에, -typecheck 만 돌리면 그 진단이 빠진다. -o /dev/null 로 결과 파일은 버린다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Motivation.swift
1
[exit 0]
진단이 하나도 없다. 그렇다면 문제는 사라진 걸까. for await 가 숨겨 둔 호출을 직접 부르는 코드로 바꿔 보면 6.4 에서 같은 문제가 어떤 모양으로 나오는지 보인다. for await 는 makeAsyncIterator() 로 iterator 를 만든 뒤 next 를 반복해서 부르는 문법 설탕이다. 아래는 그 호출을 손으로 쓴 것이다.
ExplicitNext.swift
1
2
3
4
5
6
7
8
@MainActor
func pull(_ stream: AsyncStream<NonSendable>) async {
var iterator = stream.makeAsyncIterator()
let a = await iterator.next()
let b = await iterator.next(isolation: nil)
let c = await iterator.next(isolation: #isolation)
print(a as Any, b as Any, c as Any)
}
네 번째 줄은 next(), 다섯 번째 줄은 next(isolation:) 에 nil 을, 여섯 번째 줄은 #isolation 을 넘긴다. next(isolation:) 가 무엇인지는 아래 “무엇이 바뀌나” 에서 설명하니, 지금은 “부른 쪽 isolation 을 넘기는 자리가 있다” 정도로만 읽자.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift ExplicitNext.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ExplicitNext.swift:4:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
2 | func pull(_ stream: AsyncStream<NonSendable>) async {
3 | var iterator = stream.makeAsyncIterator()
4 | let a = await iterator.next()
| |- error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated 'iterator' to @concurrent instance method 'next()' risks causing data races between @concurrent and main actor-isolated uses
5 | let b = await iterator.next(isolation: nil)
6 | let c = await iterator.next(isolation: #isolation)
ExplicitNext.swift:5:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | var iterator = stream.makeAsyncIterator()
4 | let a = await iterator.next()
5 | let b = await iterator.next(isolation: nil)
| |- error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated 'iterator' to @concurrent instance method 'next(isolation:)' risks causing data races between @concurrent and main actor-isolated uses
6 | let c = await iterator.next(isolation: #isolation)
7 | print(a as Any, b as Any, c as Any)
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
여섯 번째 줄의 #isolation 만 통과하고, next() 와 nil 을 넘긴 next(isolation:) 는 같은 에러로 막힌다. 에러 문구를 읽으면 이유가 보인다. makeAsyncIterator() 가 돌려준 iterator 는 @MainActor 함수 안의 지역 변수이고 non-Sendable 인 stream 에서 나왔으니 main actor 의 region 에 묶인다. 그런데 next() 는 nonisolated async 함수라서 @concurrent, 즉 generic executor 에서 돈다. iterator 를 main actor 에서 generic executor 로 “보내야” 하니, region 분석이 “나중에 main actor 쪽에서 쓸 때 데이터 레이스가 날 수 있다” 며 막는다. nil 을 넘긴 next(isolation:) 도 “isolation 없음” 에서 돌기 때문에 똑같이 generic executor 로 간다. #isolation 은 호출한 쪽의 isolation, 즉 MainActor 를 그대로 넘기니 경계를 넘지 않는다.
for await 가 6.4 에서 진단 없이 통과하는 것은 이 여섯 번째 줄처럼 #isolation 을 넘겨 호출하기 때문이다. 이 글 뒤쪽에서 SIL 로 직접 확인한다.
세 언어 모드로 돌리면 이 진단의 수위가 다르다.
1
bash modes.sh ExplicitNext.swift
1
2
3
4
5
6
7
=== ExplicitNext.swift [-swift-version 5]
=== ExplicitNext.swift [-swift-version 5 -strict-concurrency=complete]
ExplicitNext.swift:4:26: warning: sending 'iterator' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
ExplicitNext.swift:5:26: warning: sending 'iterator' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
=== ExplicitNext.swift [-swift-version 6]
ExplicitNext.swift:4:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
ExplicitNext.swift:5:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
modes.sh 는 위 -swift-version 6 자리에 세 가지 모드를 차례로 넣어 돌리고 error 와 warning 첫 줄만 남기는 작은 스크립트다. Swift 5 모드는 아무것도 안 내고, Swift 5 모드에 -strict-concurrency=complete 를 켜면 warning, Swift 6 모드는 error 다. 언어 모드는 컴파일러 버전과 다른 축이다. 컴파일러는 6.4 하나로 고정하고, 같은 코드를 세 모드로 돌려 본 것이다.
이 에러가 “원소가 non-Sendable 이라서” 생기는지, 아니면 “iterator 를 직접 만졌기 때문에” 생기는지는 다른 세 함수로 갈라 볼 수 있다.
SendableElem.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@MainActor
func pullInts(_ stream: AsyncStream<Int>) async {
var iterator = stream.makeAsyncIterator()
let a = await iterator.next()
print(a as Any)
}
func localOnly() async {
let stream = AsyncStream<NonSendable> { $0.yield(NonSendable()); $0.finish() }
var iterator = stream.makeAsyncIterator()
let a = await iterator.next()
print(a?.value as Any)
}
@MainActor
func localOnMain() async {
let stream = AsyncStream<NonSendable> { $0.yield(NonSendable()); $0.finish() }
var iterator = stream.makeAsyncIterator()
let a = await iterator.next()
print(a?.value as Any)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift SendableElem.swift
1
2
3
4
5
6
7
8
9
10
11
12
SendableElem.swift:19:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
17 | let stream = AsyncStream<NonSendable> { $0.yield(NonSendable()); $0.finish() }
18 | var iterator = stream.makeAsyncIterator()
19 | let a = await iterator.next()
| |- error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated 'iterator' to @concurrent instance method 'next()' risks causing data races between @concurrent and main actor-isolated uses
20 | print(a?.value as Any)
21 | }
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
세 함수 중 localOnMain 한 곳만 막힌다. 모드별로 보면 같은 모양이다.
1
bash modes.sh SendableElem.swift
1
2
3
4
5
=== SendableElem.swift [-swift-version 5]
=== SendableElem.swift [-swift-version 5 -strict-concurrency=complete]
SendableElem.swift:19:26: warning: sending 'iterator' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
=== SendableElem.swift [-swift-version 6]
SendableElem.swift:19:26: error: sending 'iterator' risks causing data races [#RegionIsolation::SendingRisksDataRace]
읽는 법은 이렇다.
pullInts: 원소가Int라AsyncStream<Int>가 Sendable 이다. 이 stream 에서 만든 iterator 는 어느 isolation 에도 묶이지 않는 독립된 region 에 있어서 generic executor 로 보내도 된다. 진단이 없다.localOnly: nonisolatedasync함수라 Swift 6 기본 설정에서는 자기도 generic executor 에서 돈다.next()호출이 isolation 경계를 넘지 않으니 iterator 를 보낼 일이 없고 진단도 없다.localOnMain: 같은 지역 stream 이지만@MainActor함수 안이다. 막힌다.
마지막이 의외일 수 있다. stream 을 만드는 build closure { $0.yield(NonSendable()); $0.finish() } 가 @MainActor 함수 안에서 만들어져 그 isolation 을 물려받기 때문이다. closure 가 main actor 에 묶이니 stream 도 main actor 의 region 에 들어간다. 이 설명이 맞는지 build closure 에 @Sendable 을 붙여 한 번 더 돌려 봤다. 아래는 내가 따로 쓴 확인용 파일이다.
V.swift
1
2
3
4
5
6
7
@MainActor
func sendableClosure() async {
let stream = AsyncStream<NonSendable> { @Sendable c in c.yield(NonSendable()); c.finish() }
var iterator = stream.makeAsyncIterator()
let a = await iterator.next()
print(a?.value as Any)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift V.swift
1
[exit 0]
closure 를 @Sendable 로 만들어 main actor 에서 떼어 놓으면 진단이 없다. SE-0420 글에서 AsyncStream<Int> 의 iterator.next() 직접 호출이 통과하던 것도 같은 이유다. 거기서는 원소가 Int 라 stream 이 Sendable 이었고, 이 글의 ExplicitNext 는 원소가 NonSendable 이라 막힌다. 두 측정이 모순이 아니라 같은 규칙에서 나온 결과다. 원소가 Sendable 이거나 stream 이 isolation 에서 떨어져 있으면 iterator 를 보내는 것이 허용되고, 아니면 막힌다.
SE-0414 의 region 분석으로 이 문제가 다 풀릴 것처럼 보이지만, 풀리는 경우가 “지역에서 만들어 지역에서만 쓰는 stream” 으로 좁다. 뒤쪽 “다른 선택지는 왜 안 됐나” 에서 이 점을 다시 다룬다.
늘 generic executor 로 가는 next()
두 번째 문제는 진단이 아니라 성능이다. nonisolated async 함수는 부른 쪽 actor 와 상관없이 generic executor 에서 돈다. next() 는 AsyncIteratorProtocol 의 requirement 중 하나이고, 프로토콜이 선언하는 next() 는 nonisolated async 다. 그래서 @MainActor 에서 for await 를 돌면, 원소를 받을 때마다 main 을 떠나 generic executor 에서 next() 를 돌고, 다시 main 으로 돌아와야 한다. 제안서는 이것을 한 문장으로 적는다. “next() always running on the generic executor is the source of unnecessary hops between an actor and the generic executor.”
이 hop 이 실제로 어디서 벌어지는지 눈으로 보려고 짧은 프로그램을 만들었다. thread 가 main 인지 pthread_main_np() 로 찍는다. OldStyle 은 예전 방식대로 next() 만 구현하고, NewStyle 은 새 방식인 next(isolation:) 만 구현한다. 새 방식이 무엇인지는 아직 설명하지 않았으니, 우선 OldStyle 줄만 본다.
Where.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Foundation
func onMain() -> String { pthread_main_np() == 1 ? "main" : "other" }
struct OldStyle: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next() async -> Int? {
n += 1
print("OldStyle.next() n=\(n) thread=\(onMain())")
return n <= 2 ? n : nil
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
struct NewStyle: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next(isolation actor: isolated (any Actor)?) async -> Int? {
n += 1
print("NewStyle.next(isolation:) n=\(n) thread=\(onMain()) actor=\(actor.map { "\(type(of: $0))" } ?? "nil")")
return n <= 2 ? n : nil
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
actor Worker {
func run() async {
for await _ in NewStyle() {}
}
}
@main
struct App {
@MainActor
static func main() async {
print("loop body on \(onMain())")
for await _ in OldStyle() {}
for await _ in NewStyle() {}
var it = NewStyle().makeAsyncIterator()
_ = await it.next()
await Worker().run()
}
}
실행 파일은 ~/se421/ 같은 짧은 경로에 두고 돌린다. 먼저 컴파일한다.
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Where.swift -o where
1
./where
1
2
3
4
5
6
7
8
9
10
11
loop body on main
OldStyle.next() n=1 thread=other
OldStyle.next() n=2 thread=other
OldStyle.next() n=3 thread=other
NewStyle.next(isolation:) n=1 thread=main actor=MainActor
NewStyle.next(isolation:) n=2 thread=main actor=MainActor
NewStyle.next(isolation:) n=3 thread=main actor=MainActor
NewStyle.next(isolation:) n=1 thread=other actor=nil
NewStyle.next(isolation:) n=1 thread=other actor=Worker
NewStyle.next(isolation:) n=2 thread=other actor=Worker
NewStyle.next(isolation:) n=3 thread=other actor=Worker
@MainActor 인 main() 은 main 에서 도는데, OldStyle.next() 는 세 번 모두 thread=other 다. 원소를 받을 때마다 main 을 떠난 것이다. 반면 NewStyle 은 같은 @MainActor 안의 for await 에서 thread=main actor=MainActor 로 돈다. 이 차이가 제안서가 말하는 “불필요한 hop” 이다.
pthread_main_np 로 main thread 인지 묻기
pthread_main_np() 는 Darwin 의 C 함수로, 지금 thread 가 process 의 main thread 면 1 을 돌려준다. Swift 의 MainActor 는 main thread 에서 돈다는 사실을 이용해서, “main actor 안에 있는가” 를 thread 로 대신 확인하는 데 썼다. Foundation 을 import 해야 쓸 수 있다.
그림 1 은 이 출력을 한 장으로 옮긴 것이다.
이 hop 을 코드 쪽에서도 세어 볼 수 있다. 두 iterator 를 @MainActor 함수에서 도는 최소한의 코드를 만든다.
Hops.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct OldStyle: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next() async -> Int? { n += 1; return n <= 2 ? n : nil }
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
struct NewStyle: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next(isolation actor: isolated (any Actor)?) async -> Int? { n += 1; return n <= 2 ? n : nil }
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
@MainActor func loopOld() async { for await _ in OldStyle() {} }
@MainActor func loopNew() async { for await _ in NewStyle() {} }
SIL 에서 hop_to_executor 는 “이 executor 로 옮겨 가라” 는 명령이다. 이 명령이 함수마다 몇 개 들어 있는지 센다. -Onone 으로 최적화를 끄고 본다. 최적화를 켜면 짧은 루프가 inline 되어 이 비교가 사라진다.
1
xcrun swiftc -emit-sil -Onone -parse-as-library -wmo -swift-version 6 Common.swift Hops.swift | xcrun swift-demangle | awk '/^sil /{c=$0} /hop_to_executor/{print c}' | sort | uniq -c
1
2
3
4
1 sil hidden @main.NewStyle.AsyncIterator.next(isolation: isolated Swift.Actor?) async -> Swift.Int?
1 sil hidden @main.OldStyle.AsyncIterator.next() async -> Swift.Int?
2 sil hidden @main.loopNew() async -> ()
3 sil hidden @main.loopOld() async -> ()
awk 가 SIL 함수 선언 줄(sil ...)을 기억해 두었다가 hop_to_executor 가 나오는 줄마다 그 함수 이름을 찍고, uniq -c 가 개수를 센다. loopOld 에는 3개, loopNew 에는 2개가 들어 있다. loopOld 의 SIL 을 열어 보면 for await 가 OldStyle.AsyncIterator.next() 를 바로 부르지 않고, AsyncIteratorProtocol 의 extension 에 있는 기본 구현 next(isolation:) 를 try_apply 로 부른다. 이 기본 구현은 throws(A.Failure) 라서 에러 경로가 따로 생기고, 세 번째 hop 은 그 에러 경로 블록에 있다. loopNew 는 NewStyle.AsyncIterator.next(isolation:) 를 apply 로 바로 부른다.
이 수치는 루프 함수 안에 들어 있는 hop 명령의 개수이지, 실행 중에 일어나는 hop 횟수가 아니다. 실행 중에 main 을 떠나는지는 위 Where 의 thread= 출력이 보여 준다.
@rethrows 와 primary associated type
세 번째 문제는 “던지느냐” 쪽이다. AsyncSequence 가 던지는 시퀀스에서만 try 를 요구하게 하려고, 지금까지는 언어의 실험 기능인 @rethrows 프로토콜을 썼다. 제안서는 이 방식이 “insufficiently general” 해서, AsyncSequence 가 primary associated type(SE-0346) 을 가지지 못하게 막아 왔다고 한다.
@rethrows 프로토콜이 6.4 에서 지금도 컴파일되는지 확인해 봤다.
RethrowsAttr.swift
1
2
3
@rethrows protocol Source {
func produce() throws -> Int
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift RethrowsAttr.swift
1
[exit 0]
Swift 5 모드로 돌려도 진단이 없다. 6.4 에서 @rethrows 프로토콜은 아직 받아들여진다. 이 기능은 Evolution 을 거치지 않은 채 들어 있던 것이라, 리뷰에서 aggie33 (#4) 가 @rethrows protocol 의 앞날을 물었고, Douglas_Gregor (#8) 가 이렇게 답했다. “Yes, we should deprecate and remove them. Assuming this proposal (or something similar to it) goes through to obviate the need for @rethrows, we’ll start staging them out soon.”
primary associated type 이 왜 필요한가는 제안서의 map 예제가 보여 준다. map 이 AsyncMapSequence 같은 구체 타입을 그대로 돌려주면 그 타입이 API 에 드러난다. 구체 타입을 숨기고 some AsyncSequence<Transformed, any Error> 로 돌려주려면, Element 와 Failure 를 <...> 로 제약할 수 있어야 한다. 이 두 associated type 을 프로토콜 선언의 <Element, Failure> 로 올리는 것이 제안의 한 축이다. 이것이 6.4 에서 어떻게 보이는지는 뒤에서 Primary.swift 로 확인한다.
무엇이 바뀌나
세 문제는 뿌리가 같다. next() 는 “어느 actor 에서 도는가” 와 “무엇을 던지는가” 를 타입이나 인자로 받을 길이 없다. 제안은 AsyncIteratorProtocol 에 새 requirement 하나와 associated type 하나를 더해서 두 가지를 모두 열어 준다. 기존 next() 는 그대로 두고, 새 것은 기본 구현을 달아 기존 conformance 가 깨지지 않게 한다.
Failure 연관 타입과 next(isolation:)
제안서가 보여 주는 프로토콜 선언의 핵심을 6.4 SDK 의 _Concurrency.swiftinterface 에서 그대로 가져왔다. 줄 번호는 이 파일의 것이다.
1
2
3
4
5
6
7
8
9
// 456~463 줄
public protocol AsyncIteratorProtocol<Element, Failure> {
associatedtype Element
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
associatedtype Failure : Swift::Error = any Swift::Error
mutating func next() async throws -> Self.Element?
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
mutating func next(isolation actor: isolated (any _Concurrency::Actor)?) async throws(Self.Failure) -> Self.Element?
}
1
2
3
4
5
// 685~689 줄
public protocol AsyncSequence<Element, Failure> {
// ... (생략)
associatedtype Failure = any Swift::Error where Self.Failure == Self.AsyncIterator.Failure
}
세 가지가 바뀌었다.
Failure: 새 associated type 이다.Error를 따르고, 기본값은any Error다. 기본값이 있으니Failure를 몰라도 기존 타입은 그대로any Error로 취급된다.next(isolation:): 새 requirement 다.isolated (any Actor)?를 받고,throws(Self.Failure)로 던진다.- 프로토콜 이름 옆의
<Element, Failure>: 두 associated type 이 primary associated type 이 되었다.any AsyncSequence<String, any Error>나some AsyncSequence<Int, Never>처럼 쓸 수 있다는 뜻이다.
AsyncIteratorProtocol 과 AsyncSequence 는 각각 “값을 하나씩 꺼내는 쪽” 과 “그 꺼내는 쪽을 만들어 주는 쪽” 이다. for await 는 makeAsyncIterator() 로 iterator 를 만들고 next 를 반복해서 부른다. 원소는 둘 다 Element 이고, 던지는 에러는 이번에 둘 다 Failure 로 드러났다. AsyncSequence 의 Failure 는 AsyncIterator.Failure 와 같아야 한다는 제약이 붙어 있다.
새로 더해진 Failure 와 next(isolation:) 는 macOS 15, iOS 18, watchOS 11, tvOS 18, visionOS 2 이상에서만 있다. 프로토콜 자체는 10.15 부터 있었고, 6.0 표준 라이브러리에서 AsyncIteratorProtocol 의 witness table 에 새 항목이 생기는 것이라서다. 이 availability 가 곳곳에 나타나는 이야기는 “배포 대상 OS” 절에서 한다.
isolated 인자로 부른 쪽 actor 받기
isolated (any Actor)? 는 isolated parameter 의 한 형태다. SE-0313 은 isolated 를 non-optional actor 타입에만 허용했다. 여기서 쓴 (any Actor)? 는 John McCall 의 isolation inheritance pitch 가 이를 일반화한 형태이고, 그 규칙은 SE-0420 에 들어갔다. 함수 인자에 isolated 를 붙이면, 그 함수의 본문은 그 인자가 가리키는 actor 의 isolation 에서 돈다. 보통은 isolated MyActor 처럼 구체 타입을 쓰는데, 여기서는 (any Actor)? 다. any Actor 는 어떤 actor 든 담는 existential 타입이고, 끝의 ? 는 “없음” 도 허용한다. 값이 nil 이면 isolation 이 없는 nonisolated 로 돈다. Actor 는 이 모든 actor 가 따르는 프로토콜이다.
왜 구체 타입이 아니라 existential 일까. 이 선택은 “다른 선택지는 왜 안 됐나” 에서 따로 다룬다. 여기서는 (any Actor)? 하나로 MainActor, 임의의 actor 인스턴스, nil(nonisolated) 을 모두 받을 수 있다는 점만 짚는다.
for await 가 실제로 어떻게 부르는지 앞의 Motivation.swift 로 SIL 을 열어 본다. 루프 머리(loop header) 부분이다.
1
xcrun swiftc -emit-sil -parse-as-library -wmo -swift-version 6 Common.swift Motivation.swift | xcrun swift-demangle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bb1: // Preds: bb2 bb0
%10 = alloc_stack $Optional<NonSendable> // users: %22, %26, %59, %18
%11 = metatype $@thick MainActor.Type // user: %13
// function_ref static MainActor.shared.getter
%12 = function_ref @static Swift.MainActor.shared.getter : Swift.MainActor : $@convention(method) (@thick MainActor.Type) -> @owned MainActor // user: %13
%13 = apply %12(%11) : $@convention(method) (@thick MainActor.Type) -> @owned MainActor // user: %14
%14 = init_existential_ref %13 : $MainActor : $MainActor, $any Actor // user: %15
%15 = enum $Optional<any Actor>, #Optional.some!enumelt, %14 // users: %20, %18
%16 = begin_access [modify] [static] %6 // users: %19, %18
// function_ref AsyncStream.Iterator.next(isolation:)
%17 = function_ref @Swift.AsyncStream.Iterator.next(isolation: isolated Swift.Actor?) async -> A? : $@convention(method) @async <τ_0_0> (@sil_isolated @guaranteed Optional<any Actor>, @inout AsyncStream<τ_0_0>.Iterator) -> @out Optional<τ_0_0> // user: %18
%18 = apply %17<NonSendable>(%10, %15, %16) : $@convention(method) @async <τ_0_0> (@sil_isolated @guaranteed Optional<any Actor>, @inout AsyncStream<τ_0_0>.Iterator) -> @out Optional<τ_0_0>
end_access %16 // id: %19
release_value %15 // id: %20
hop_to_executor %4 // id: %21
MainActor.shared 를 얻어서, any Actor 로 감싸고(init_existential_ref), Optional.some 으로 한 번 더 감싼 값을 AsyncStream.Iterator.next(isolation:) 에 넘긴다. SE-0420 글에서 본 #isolation 이 이렇게 풀린다. @MainActor 함수 안이라서 호출한 쪽 isolation 이 MainActor 이고, 그 값이 그대로 인자로 간다. 호출이 돌아오면 바로 hop_to_executor %4 로 main actor 를 다시 확인한다. 이 호출은 main 을 벗어나지 않았으니 실제로 옮겨 갈 일은 없다.
실행 위치
위 Where.swift 출력의 NewStyle 줄을 하나씩 읽는다.
1
2
3
4
5
6
7
NewStyle.next(isolation:) n=1 thread=main actor=MainActor
NewStyle.next(isolation:) n=2 thread=main actor=MainActor
NewStyle.next(isolation:) n=3 thread=main actor=MainActor
NewStyle.next(isolation:) n=1 thread=other actor=nil
NewStyle.next(isolation:) n=1 thread=other actor=Worker
NewStyle.next(isolation:) n=2 thread=other actor=Worker
NewStyle.next(isolation:) n=3 thread=other actor=Worker
- 앞의 세 줄은
@MainActor의for await이다.next(isolation:)가MainActor를 받아서 main thread 에서 돈다. 인자actor를 찍으면MainActor다. - 네 번째 줄은
it.next()를 직접 부른 호출이다. 기본next()가next(isolation: nil)을 부르기 때문에actor=nil이고, generic executor 에서 돈다. - 마지막 세 줄은
actor Worker안에서for await를 돈 것이다. 받은 isolation 이Worker이고, thread 는 main 이 아닌 곳이다. actor 는 main thread 가 아닌 곳에서 돌고, 그 actor 의 isolation 이next(isolation:)에 그대로 전달된다.
next(isolation:) 는 부른 쪽의 isolation 을 값으로 받기 때문에, 하나의 구현이 어느 actor 에서 불리든 그 actor 에서 돈다. 이 값을 안 쓰는 구현이어도 isolated 인자가 있으면 본문이 그 isolation 에서 돈다는 점이 중요하다. 위 NewStyle.next(isolation:) 는 actor 를 출력에만 썼을 뿐 다른 데서는 쓰지 않는다.
Swift 6.4 에는 nonisolated 함수를 부른 쪽 actor 에서 돌게 하는 방식으로 바꾸는 upcoming feature NonisolatedNonsendingByDefault 가 있다. 이 기능은 SE-0461 에서 나온다. 이 기능을 켜면 OldStyle 은 달라질까. 같은 코드를 이 feature 를 켜고 다시 빌드해서 돌려 봤다.
1
xcrun swiftc -parse-as-library -swift-version 6 -enable-upcoming-feature NonisolatedNonsendingByDefault Common.swift Where.swift -o where-nonsending
1
./where-nonsending
출력은 위 ./where 와 글자 그대로 같다. feature 를 켜면 OldStyle.next() 자체는 부른 쪽 isolation 을 받는 함수가 된다. 그런데 표준 라이브러리가 선언한 requirement next() 는 여전히 @concurrent 라서, 컴파일러가 만든 witness thunk 가 nil, 곧 generic executor 로 옮긴 뒤 OldStyle.next() 를 부른다. for await 가 넘긴 MainActor 는 기본 next(isolation:) 에서 끊긴다.
두 기본 구현
새 requirement 에는 기본 구현이 필요하다. 기존 iterator 는 next() 만 구현하고 있으니 next(isolation:) 의 기본 구현이 그 next() 를 불러야 한다. 반대로 새 iterator 는 next(isolation:) 만 구현하고 싶으니, 기본 next() 가 next(isolation: nil) 을 불러야 한다. 제안은 두 기본 구현을 서로의 관점에서 쓴다. 6.4 인터페이스에서 가져왔다.
1
2
3
4
5
6
7
8
// 467 줄
@inlinable public mutating func next(isolation actor: isolated (any _Concurrency::Actor)?) async throws(Self.Failure) -> Self.Element? {
do {
return try await next()
} catch {
throw error as! Failure
}
}
1
2
3
4
// 478 줄
@inlinable public mutating func next() async throws(Self.Failure) -> Self.Element? {
return try await next(isolation: nil)
}
6.4 에서 측정하면 next(isolation:) 기본 구현에는 @available(macOS 15.0, ...) 와 @inlinable 이 붙어 있고, deprecated 같은 attribute 는 없다. 본문은 next() 를 부르고, 에러는 Failure 로 강제로 내려서 던진다.
이 두 기본 구현 때문에, 구현해야 할 최소는 next() 와 next(isolation:) 중 하나가 된다. 세 가지 경우를 직접 빌드했다.
OnlyNext.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Counter: AsyncSequence {
let limit: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current = 0
let limit: Int
mutating func next() async -> Int? {
guard current < limit else { return nil }
current += 1
return current
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator(limit: limit) }
}
OnlyIsolation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct MyError: Error {}
struct Ticker: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var count = 0
mutating func next(isolation actor: isolated (any Actor)?) async throws(MyError) -> Int? {
count += 1
if count > 3 { throw MyError() }
return count
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
func check() {
let _: MyError.Type = Ticker.Failure.self
let _: MyError.Type = Ticker.AsyncIterator.Failure.self
}
next() 만 구현한 Counter 는 Swift 5, 5 complete, 6 모드 모두 진단이 없다. 배포 대상을 macOS 14 로 낮춰도 없다. next(isolation:) 만 구현한 Ticker 도 세 모드 모두 진단이 없다. OnlyIsolation.swift 의 check() 에서 Ticker.Failure.self 가 MyError.Type 에 대입되는 것이 컴파일되는 것으로 보아, next(isolation:) 가 throws(MyError) 로 던지면 Failure 가 MyError 로 추론된다. 제안서는 이것을 “associated type inference” 규칙으로 적는다. next(isolation:) 를 구현한 타입은 그 함수의 throws 에서 Failure 를 추론하고, 기본 구현을 쓰는 타입은 next() 의 throws 에서 추론한다. 안 던지는 next() 는 Never 가 된다.
그러면 둘 다 구현하지 않으면 어떻게 될까.
Neither.swift
1
2
3
struct Empty: AsyncIteratorProtocol {
typealias Element = Int
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Neither.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
Neither.swift:1:8: error: type 'Empty' does not conform to protocol 'AsyncIteratorProtocol'
1 | struct Empty: AsyncIteratorProtocol {
| `- error: type 'Empty' does not conform to protocol 'AsyncIteratorProtocol'
2 | typealias Element = Int
3 | }
_Concurrency.AsyncIteratorProtocol.Failure:3:18: note: protocol requires nested type 'Failure'
1 | protocol AsyncIteratorProtocol {
2 | @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
3 | associatedtype Failure : Error = any Error}
| `- note: protocol requires nested type 'Failure'
4 |
[exit 1]
에러 note 는 Failure 라는 nested type 이 필요하다고 말한다. 구현한 next 가 없으니 Failure 를 추론할 근거가 없다. 그래서 Failure 를 직접 적어 주면 어떻게 될까.
NeitherFailure.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Foundation
struct Loop: AsyncIteratorProtocol {
typealias Element = Int
typealias Failure = Never
}
@main
struct App {
static func main() async {
var it = Loop()
print("start"); fflush(stdout)
let x = await it.next(isolation: nil)
print(x as Any)
}
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift NeitherFailure.swift
1
[exit 0]
진단이 0개로 빌드된다. 컴파일러는 Loop 이 next 를 하나도 구현하지 않았다는 것을 잡지 못한다. 두 requirement 모두 기본 구현이 witness 로 채워지고, 6.4 의 기본 next(isolation:) 에는 deprecated 가 없어서 뒤에서 볼 witness 규칙도 걸리지 않기 때문이다. 이 프로그램을 실행하면 어떻게 될까. 메모리를 많이 먹으니 timeout 8 로 감싸서 돌린다.
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift NeitherFailure.swift -o neither
1
/usr/bin/time -l timeout 8 ./neither
1
start
start 를 찍고 멈춘다. 8초 뒤 timeout 이 끝내고 종료 코드는 124 다. /usr/bin/time -l 의 maximum resident set size 는 두 번 돌려서 10537598976 바이트와 13124845568 바이트, 곧 약 10.5 GB 와 13.1 GB 가 나왔고, 돌 때마다 값이 달랐다. 기본 next() 와 기본 next(isolation:) 이 서로를 부르며 끝나지 않고, 그동안 메모리가 계속 늘어난다.
제안서는 이 상황을 한 문장으로 적어 두었다. “Both function requirements of AsyncIteratorProtocol have default implementations that are written in terms of each other, meaning that it is a programmer error to implement neither of them.” 그림 2 가 세 경우를 한 장으로 요약한다.
OnlyNext, OnlyIsolation 은 구현한 쪽이 순환을 끊어 주니 문제없다. NeitherFailure 처럼 Failure 를 손으로 적어 추론 에러를 피하면, 빌드 단계에서는 잡히지 않고 실행 단계에서 끝나지 않는다.
기본 구현에 대한 availability 규칙
제안은 이 위험을 줄이려고 컴파일러에 새 규칙을 하나 더한다. 제안서 문장은 이렇다. “we add a new availability rule where the witness checker diagnoses a protocol conformance that uses an deprecated, obsoleted, or unavailable default witness implementation. Deprecated implementations will produce a warning, while obsoleted and unavailable implementations will produce an error.” 요구사항을 기본 구현으로 채우는 conformance 가 있을 때, 그 기본 구현이 deprecated 면 경고를, obsoleted 나 unavailable 이면 에러를 낸다는 것이다. 이 규칙이 사용자 프로토콜에서 실제로 어떻게 나오는지 두 가지 기본 구현으로 확인했다.
DeprecatedWitness.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protocol Greeter {
func hello() -> String
}
extension Greeter {
@available(*, deprecated, message: "Implement hello() yourself")
func hello() -> String { "default" }
}
struct English: Greeter {}
protocol Shouter {
func shout() -> String
}
extension Shouter {
@available(*, unavailable, message: "Implement shout() yourself")
func shout() -> String { "DEFAULT" }
}
struct Quiet: Shouter {}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift DeprecatedWitness.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
DeprecatedWitness.swift:10:8: warning: deprecated default implementation is used to satisfy instance method 'hello()' required by protocol 'Greeter': Implement hello() yourself [#DeprecatedDeclaration]
1 | protocol Greeter {
2 | func hello() -> String
| `- note: requirement 'hello()' declared here
3 | }
4 |
5 | extension Greeter {
6 | @available(*, deprecated, message: "Implement hello() yourself")
7 | func hello() -> String { "default" }
| `- note: 'hello()' declared here
8 | }
9 |
10 | struct English: Greeter {}
| `- warning: deprecated default implementation is used to satisfy instance method 'hello()' required by protocol 'Greeter': Implement hello() yourself [#DeprecatedDeclaration]
11 |
12 | protocol Shouter {
DeprecatedWitness.swift:21:8: error: type 'Quiet' does not conform to protocol 'Shouter'
19 | }
20 |
21 | struct Quiet: Shouter {}
| `- error: type 'Quiet' does not conform to protocol 'Shouter'
22 |
DeprecatedWitness.swift:21:8: error: unavailable instance method 'shout()' was used to satisfy a requirement of protocol 'Shouter': Implement shout() yourself
11 |
12 | protocol Shouter {
13 | func shout() -> String
| `- note: requirement 'shout()' declared here
14 | }
15 |
16 | extension Shouter {
17 | @available(*, unavailable, message: "Implement shout() yourself")
18 | func shout() -> String { "DEFAULT" }
| `- note: 'shout()' declared here
19 | }
20 |
21 | struct Quiet: Shouter {}
| `- error: unavailable instance method 'shout()' was used to satisfy a requirement of protocol 'Shouter': Implement shout() yourself
22 |
[#DeprecatedDeclaration]: <https://docs.swift.org/compiler/documentation/diagnostics/deprecated-declaration>
[exit 1]
English 의 hello() 는 deprecated 기본 구현으로 채워져서 경고가 나고, Quiet 의 shout() 는 unavailable 기본 구현으로 채워져서 에러가 난다. 규칙이 6.4 에서 동작한다. 같은 6.4 의 표준 라이브러리 next(isolation:) 기본 구현에는 앞에서 본 것처럼 deprecated 가 붙어 있지 않아서, next() 만 구현한 OnlyNext 에는 경고가 나오지 않았다. 규칙은 동작하지만 표준 라이브러리의 이 기본 구현은 그 규칙의 대상이 아니라는 것이 측정 결과다.
이 규칙이 어디서 왔는지는 피치 스레드가 보여 준다. 제안서는 이 규칙을 “새 availability 규칙” 으로 소개한다. xwu (#5) 는 표준 라이브러리에 기본 구현끼리 서로 부르는 곳이 이미 있고 거기서는 availability attribute 로 알맞은 진단을 내는 방법을 찾았으니, 정말 “새 규칙” 이 필요한지부터 확인하자고 했다. 이어서 hborla (#14) 가 Language Steering Group 에서 이 부분을 논의했다고 전했다. “The witness checker already diagnoses using default implementations that are unavailable or obsoleted, so the fact that deprecation isn’t considered is just a compiler bug.” 그리고 기본 구현은 “unconditionally deprecated, and obsoleted in Swift 6” 로 만들고 싶다고 덧붙였다. 즉 unavailable 과 obsoleted 는 원래 witness checker 가 진단하고 있었고, deprecated 만 빠져 있던 것이 컴파일러 버그였다는 설명이다. 위 DeprecatedWitness 출력에서 unavailable 은 에러, deprecated 는 경고로 나오는 것이 그 결과다.
mklbtz (#6) 는 이 규칙이 이 pitch 밖에서도 쓸모가 있어 보인다고 했다. 자기도 같은 기능이 필요한 곳이 있고, deprecated 기본 구현을 물려받는 conformance 가 경고로 진단되는 것이 반갑다는 것이다. 같은 글에서 mklbtz 는 John McCall 의 “Inheriting the caller’s actor isolation” pitch 와 겹치는 생각이 있다면서, nextElement 에 = #isolation 기본 인자를 쓰거나 @inheritsIsolation 을 쓸 계획은 없느냐고 물었다. 당시 초안은 이 메서드를 nextElement 로 불렀다. 이 질문은 “다른 선택지는 왜 안 됐나” 에서 이어 본다.
배포 대상 OS
새 requirement 와 Failure 는 6.0 표준 라이브러리에만 있다. 그래서 배포 대상(deployment target)이 macOS 15 미만이면 컴파일러가 하는 일이 달라진다. 제안서는 이렇게 쓴다. for-in 은 “context 의 availability 가 알맞을 때” 만 next(isolation:) 를 부르고, 그렇지 않으면 예전처럼 next() 를 부른다. 같은 Motivation.swift 를 -target arm64-apple-macos14 로 빌드하면 진단은 여전히 0개이고, SIL 의 루프 머리는 이렇게 바뀐다.
1
xcrun swiftc -emit-sil -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Common.swift Motivation.swift | xcrun swift-demangle
1
2
3
4
5
6
7
8
bb1: // Preds: bb2 bb0
%10 = alloc_stack $Optional<NonSendable> // users: %16, %20, %53, %13
%11 = begin_access [modify] [static] %6 // users: %14, %13
// function_ref AsyncStream.Iterator.next()
%12 = function_ref @Swift.AsyncStream.Iterator.next() async -> A? : $@convention(method) @async <τ_0_0> (@inout AsyncStream<τ_0_0>.Iterator) -> @out Optional<τ_0_0> // user: %13
%13 = apply %12<NonSendable>(%10, %11) : $@convention(method) @async <τ_0_0> (@inout AsyncStream<τ_0_0>.Iterator) -> @out Optional<τ_0_0>
end_access %11 // id: %14
hop_to_executor %4 // id: %15
macOS 15 미만을 지원하는 자기 iterator 는 어떨까. next(isolation:) 만 구현한 타입을 macOS 14 대상으로 빌드해 봤다.
OldTarget.swift
1
2
3
4
5
6
7
8
9
10
11
struct NewOnly: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var done = false
mutating func next(isolation actor: isolated (any Actor)?) async -> Int? {
if done { return nil }
done = true
return 1
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
기본 target 에서는 진단이 0개다. macOS 14 로 낮추면 이렇게 된다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Common.swift OldTarget.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
OldTarget.swift:2:10: error: protocol 'AsyncIteratorProtocol' requires 'next()' to be available in macOS 14 and newer
1 | struct NewOnly: AsyncSequence {
2 | struct AsyncIterator: AsyncIteratorProtocol {
| `- error: protocol 'AsyncIteratorProtocol' requires 'next()' to be available in macOS 14 and newer
3 | var done = false
4 | mutating func next(isolation actor: isolated (any Actor)?) async -> Int? {
_Concurrency.AsyncIteratorProtocol.next:3:35: note: 'next()' declared here
1 | protocol AsyncIteratorProtocol {
2 | @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
3 | @inlinable public mutating func next() async throws(Self.Failure) -> Self.Element?}
| `- note: 'next()' declared here
4 |
_Concurrency.AsyncIteratorProtocol.next:2:15: note: protocol requirement here
1 | protocol AsyncIteratorProtocol {
2 | mutating func next() async throws -> Self.Element?}
| `- note: protocol requirement here
3 |
[exit 1]
기본 next() 가 @available(macOS 15.0, ...) 라서, macOS 14 에서 AsyncIteratorProtocol 의 next() requirement 를 채울 기본 구현이 없다는 에러다. 제안서가 “Implications on adoption” 에서 적은 바로 그 내용이다. 6.0 표준 라이브러리보다 먼저 쓸 수 있는 타입은 next() 를 직접 구현해야 한다. macOS 15 미만도 지원하는 iterator 는 next() 를 남겨 두고, 새 next(isolation:) 를 같이 구현하는 것이 길이다.
같은 이유로 primary associated type 도 macOS 15 이상에서만 쓸 수 있다. 뒤에서 볼 Primary.swift 를 macOS 14 로 빌드하면 아래처럼 나온다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Common.swift Primary.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
25
26
27
28
29
30
31
32
33
34
35
36
Primary.swift:2:47: error: 'Failure' is only available in macOS 15.0 or newer
1 | protocol Feed {
| `- note: add '@available' attribute to enclosing protocol
2 | func updates() -> any AsyncSequence<String, any Error>
| | `- error: 'Failure' is only available in macOS 15.0 or newer
| `- note: add '@available' attribute to enclosing instance method
3 | }
4 |
Primary.swift:5:41: error: 'Failure' is only available in macOS 15.0 or newer
3 | }
4 |
5 | func evens() -> some AsyncSequence<Int, Never> {
| | `- error: 'Failure' is only available in macOS 15.0 or newer
| `- note: add '@available' attribute to enclosing global function
6 | AsyncStream<Int> { c in
7 | for i in 0..<6 { c.yield(i) }
Primary.swift:17:21: error: member 'map' cannot be used on value of type 'any AsyncSequence<String, any Error>'; consider using a generic constraint instead [#ExistentialMemberAccess]
15 | print(line)
16 | }
17 | let mapped = feed.updates().map { $0.uppercased() }
| `- error: member 'map' cannot be used on value of type 'any AsyncSequence<String, any Error>'; consider using a generic constraint instead [#ExistentialMemberAccess]
18 | _ = mapped
19 | }
Primary.swift:22:3: error: call can throw, but it is not marked with 'try' and the error is not handled
20 |
21 | func useEvens() async {
22 | for await x in evens() { print(x) }
| `- error: call can throw, but it is not marked with 'try' and the error is not handled
23 | }
24 |
[#ExistentialMemberAccess]: <https://docs.swift.org/compiler/documentation/diagnostics/existential-member-access-limitations>
[exit 1]
2:47 과 5:41 은 any AsyncSequence<String, any Error> 와 some AsyncSequence<Int, Never> 의 Failure 자리가 macOS 15 이상에서만 쓸 수 있다는 에러다. 제안서도 primary associated type 은 Swift 6.0 availability 뒤에 있어야 한다고 쓴다. 17:21 은 기본 target 에서도 나온 map 에러다. 22:3 은 for await x in evens() 가 macOS 14 에서는 던질 수 있는 next() 로 컴파일되어 try 가 없다는 에러다. macOS 14 에서는 Failure 를 쓸 수 없어서, evens() 가 돌려주는 시퀀스의 Failure 가 Never 라는 것을 루프가 이용하지 못하기 때문이다.
for try await 의 에러 타입을 보는 InferCheck.swift 의 macOS 14 결과는 바로 아래 절에서 본다.
for try await 의 에러 타입
next(isolation:) 가 throws(Self.Failure) 로 던지는 것이 이 제안의 “던지느냐” 쪽 해법이다. throws(Self.Failure) 가 낯설면 먼저 typed throws 를 알아야 한다. 아직 이 블로그에 typed throws 글이 없어서 여기서 필요한 만큼만 설명한다. 원문은 SE-0413: Typed throws 다.
Swift 의 throws 는 원래 “무슨 에러인지는 말하지 않는다” 는 뜻이다. 던질 수 있는 에러의 타입이 any Error 이고, 받는 쪽은 catch 안에서 error 가 any Error 라는 것밖에 모른다. SE-0413 은 이 자리에 타입을 적게 한다. func load() throws(LoadError) 처럼 쓰면 이 함수가 던지는 것은 LoadError 뿐이고, 받는 쪽의 catch 안에서 error 는 LoadError 로 취급된다. throws 만 적는 것은 throws(any Error) 와 같은 뜻이다.
특별한 경우가 하나 있다. throws(Never) 는 “던질 수 있는 에러가 없다” 는 뜻이라 안 던지는 함수와 같다. 에러 타입을 generic 으로 받는 함수에 Never 가 들어오면 그 함수는 안 던지는 함수가 되어 try 가 필요 없다. 이 제안의 Failure 가 정확히 이 구조다. AsyncStream 의 Failure 는 Never 이고, AsyncThrowingStream 은 generic parameter Failure 를 그대로 쓰고, 흔히 쓰는 AsyncThrowingStream<Int, any Error> 라면 any Error 다. 같은 next(isolation:) 가 throws(Self.Failure) 하나로 두 경우를 다 표현한다.
타입 있는 throws 는 Failure 를 모른 채 쓰는 코드에서도 Failure 를 이용할 수 있게 한다. 제네릭 함수가 throws(S.Failure) 로 시퀀스의 에러를 그대로 내보내는 식이다. 이 글의 sum 함수가 뒤에서 보여 준다.
typed throws 가 for try await 에서 어떻게 드러나는지 보려고, 두 가지 시퀀스를 만들었다. Throwing 은 세 번째 원소에서 MyError 를 던지고, Quiet 는 안 던진다.
Inference.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
struct MyError: Error {}
struct Throwing: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next(isolation actor: isolated (any Actor)?) async throws(MyError) -> Int? {
n += 1
if n == 3 { throw MyError() }
return n
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
struct Quiet: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
var n = 0
mutating func next(isolation actor: isolated (any Actor)?) async -> Int? {
n += 1
return n <= 2 ? n : nil
}
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
func concrete<S: AsyncSequence>(_ s: S) where S.AsyncIterator == Throwing.AsyncIterator {
let closure = {
for try await element in s { print(element) }
}
print(type(of: closure))
}
func never<S: AsyncSequence>(_ s: S) where S.AsyncIterator == Quiet.AsyncIterator {
let closure = {
for await element in s { print(element) }
}
print(type(of: closure))
}
func generic<S: AsyncSequence>(_ s: S) {
let closure = {
for try await element in s { print(element) }
}
print(type(of: closure))
}
func generic2<S: AsyncSequence>(_ s: S) where S.Failure == Never {
let closure = {
for await element in s { print(element) }
}
print(type(of: closure))
}
func caught() async {
do {
for try await x in Throwing() { print("got", x) }
} catch {
let e: MyError = error
print("caught", type(of: e))
}
}
@main
struct App {
static func main() async {
concrete(Throwing())
never(Quiet())
generic(Throwing())
generic2(Quiet())
await caught()
}
}
제안서가 설명하는 세 경우에 S.Failure == Never 만 건 경우를 하나 더해 코드로 옮겼다. 이 글의 generic 은 기본 target 에서 도는 경우이고, 제안서의 any Error 경우는 Failure 를 쓸 수 있는 배포 대상을 전제로 한다. concrete 는 iterator 타입이 Throwing.AsyncIterator 로 정해진 경우, never 는 Quiet.AsyncIterator 로 정해진 경우, generic 은 아무 제약이 없는 경우, generic2 는 S.Failure == Never 만 있는 경우다. 각각 for 루프를 담은 closure 를 만들어 type(of:) 로 타입을 찍는다. caught 는 catch 안에서 error 를 MyError 로 직접 받아 본다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Inference.swift
1
[exit 0]
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Inference.swift -o inference
1
./inference
1
2
3
4
5
6
7
() async throws -> ()
() async -> ()
() async throws -> ()
() async -> ()
got 1
got 2
caught MyError
빌드는 진단 없이 끝나고, caught() 의 let e: MyError = error 도 컴파일된다. iterator 타입이 Throwing.AsyncIterator 로 정해진 경우에 catch 의 error 를 MyError 로 받을 수 있다는 뜻이다. 실행 결과도 got 1, got 2 뒤에 caught MyError 다. 던지는 시퀀스는 try 가 필요하고 안 던지는 시퀀스는 for await 하나로 된다는 것도 위 네 줄에서 보인다. 한 가지 특이한 점이 있다. type(of: closure) 가 iterator 타입이 정해진 Throwing 을 도는 경우에도 () async throws -> () 로 찍힌다. 런타임은 throws(MyError) 가 붙은 함수 타입이면 이름에 그대로 찍으므로, 이 closure 의 thrown type 이 실제로 any Error 로 추론되었다는 뜻이다. do/catch 안의 error 는 MyError 로 확정되지만 closure 타입 추론은 any Error 라는 차이는 바로 아래 InferCheck.swift 가 에러로 보여 준다.
closure 의 타입이 () async throws(MyError) -> Void 자리에 들어가는지 확인했다.
InferCheck.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
25
26
27
struct MyError: Error {}
struct Throwing: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
mutating func next(isolation actor: isolated (any Actor)?) async throws(MyError) -> Int? { nil }
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
func concrete<S: AsyncSequence>(_ s: S) where S.AsyncIterator == Throwing.AsyncIterator {
let closure = {
for try await element in s { print(element) }
}
let _: () async throws(MyError) -> Void = closure
}
func generic<S: AsyncSequence>(_ s: S) {
let closure = {
for try await element in s { print(element) }
}
let _: () async throws(MyError) -> Void = closure
}
func annotated() {
let f: () throws(MyError) -> Void = {}
print(type(of: f))
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift InferCheck.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
InferCheck.swift:14:45: error: invalid conversion of thrown error type 'any Error' to 'MyError'
12 | for try await element in s { print(element) }
13 | }
14 | let _: () async throws(MyError) -> Void = closure
| `- error: invalid conversion of thrown error type 'any Error' to 'MyError'
15 | }
16 |
InferCheck.swift:21:45: error: invalid conversion of thrown error type 'any Error' to 'MyError'
19 | for try await element in s { print(element) }
20 | }
21 | let _: () async throws(MyError) -> Void = closure
| `- error: invalid conversion of thrown error type 'any Error' to 'MyError'
22 | }
23 |
[exit 1]
타입 주석 없는 closure 의 thrown type 은 any Error 로 잡힌다. 14:45 는 iterator 가 Throwing.AsyncIterator 로 정해진 concrete 이고, 21:45 는 제약이 없는 generic 이다. 두 경우 모두 MyError 로 바꿀 수 없다는 에러다. for try await 의 catch 안에서 error 가 MyError 로 보이는 것은 위 caught() 처럼 do/catch 문 안에서다. closure 의 타입을 추론하는 쪽은 any Error 다. 이 차이를 피하는 방법은 closure 나 함수의 thrown type 을 직접 적는 것이다.
-enable-experimental-feature FullTypedThrows 로 이 추론을 켜 보려 하면 이렇게 나온다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-experimental-feature FullTypedThrows Common.swift InferCheck.swift
1
2
<unknown>:0: error: experimental feature 'FullTypedThrows' cannot be enabled in production compiler
[exit 1]
production 컴파일러에서는 이 feature 를 켤 수 없다. 이 글의 측정은 그 feature 없이 한 것이다.
배포 대상을 macOS 14 로 낮추면 같은 파일에서 에러가 세 개 더 나온다. 아래 출력에서 4:10, 12:5, 26:9 가 더해진 에러다. -target arm64-apple-macos14 를 붙여 돌렸다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Common.swift InferCheck.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
InferCheck.swift:4:10: error: protocol 'AsyncIteratorProtocol' requires 'next()' to be available in macOS 14 and newer
2 |
3 | struct Throwing: AsyncSequence {
4 | struct AsyncIterator: AsyncIteratorProtocol {
| `- error: protocol 'AsyncIteratorProtocol' requires 'next()' to be available in macOS 14 and newer
5 | mutating func next(isolation actor: isolated (any Actor)?) async throws(MyError) -> Int? { nil }
6 | }
_Concurrency.AsyncIteratorProtocol.next:3:35: note: 'next()' declared here
1 | protocol AsyncIteratorProtocol {
2 | @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
3 | @inlinable public mutating func next() async throws(Self.Failure) -> Self.Element?}
| `- note: 'next()' declared here
4 |
_Concurrency.AsyncIteratorProtocol.next:2:15: note: protocol requirement here
1 | protocol AsyncIteratorProtocol {
2 | mutating func next() async throws -> Self.Element?}
| `- note: protocol requirement here
3 |
InferCheck.swift:14:45: error: invalid conversion of thrown error type 'any Error' to 'MyError'
12 | for try await element in s { print(element) }
13 | }
14 | let _: () async throws(MyError) -> Void = closure
| `- error: invalid conversion of thrown error type 'any Error' to 'MyError'
15 | }
16 |
InferCheck.swift:12:5: error: 'next()' is only available in macOS 15.0 or newer
8 | }
9 |
10 | func concrete<S: AsyncSequence>(_ s: S) where S.AsyncIterator == Throwing.AsyncIterator {
| `- note: add '@available' attribute to enclosing global function
11 | let closure = {
12 | for try await element in s { print(element) }
| |- error: 'next()' is only available in macOS 15.0 or newer
| `- note: add 'if #available' version check
13 | }
14 | let _: () async throws(MyError) -> Void = closure
InferCheck.swift:21:45: error: invalid conversion of thrown error type 'any Error' to 'MyError'
19 | for try await element in s { print(element) }
20 | }
21 | let _: () async throws(MyError) -> Void = closure
| `- error: invalid conversion of thrown error type 'any Error' to 'MyError'
22 | }
23 |
InferCheck.swift:26:9: error: runtime support for typed throws function types is only available in macOS 15.0.0 or newer
22 | }
23 |
24 | func annotated() {
| `- note: add '@available' attribute to enclosing global function
25 | let f: () throws(MyError) -> Void = {}
26 | print(type(of: f))
| |- error: runtime support for typed throws function types is only available in macOS 15.0.0 or newer
| `- note: add 'if #available' version check
27 | }
28 |
[exit 1]
4:10 은 위 OldTarget 과 같은 에러다. 12:5 는 for try await 가 next() 를 쓰는데 그 next() 가 macOS 15 이상이라는 에러다. 26:9 는 type(of: f) 가 typed throws 함수 타입의 런타임 metadata 를 필요로 하는데, 그 런타임 지원이 macOS 15 이상에만 있다는 에러다. 이 세 에러는 이 코드가 Failure 와 typed throws 를 건드리기 때문에 나온다.
타입을 직접 적으면 어떻게 될까. 아래 TypedFunc.swift 는 같은 일을 타입을 적어서 한다.
TypedFunc.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct MyError: Error {}
struct Throwing: AsyncSequence {
struct AsyncIterator: AsyncIteratorProtocol {
mutating func next(isolation actor: isolated (any Actor)?) async throws(MyError) -> Int? { nil }
}
func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}
func explicitClosure() {
let closure = { () async throws(MyError) -> Void in
for try await element in Throwing() { print(element) }
}
_ = closure
}
func concreteFunc() async throws(MyError) {
for try await element in Throwing() { print(element) }
}
func sum<S: AsyncSequence<Int, F>, F: Error>(_ s: S) async throws(F) -> Int {
var total = 0
for try await x in s { total += x }
return total
}
func neverSum(_ s: some AsyncSequence<Int, Never>) async -> Int {
var total = 0
for await x in s { total += x }
return total
}
func streams() async throws(MyError) {
let quiet = AsyncStream<Int> { $0.yield(1); $0.finish() }
let n = await neverSum(quiet)
let m = await sum(quiet)
let k = try await sum(Throwing())
print(n, m, k)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift TypedFunc.swift
1
[exit 0]
세 모드 모두 진단이 없다. 읽는 법은 이렇다.
explicitClosure: closure 의 thrown type 을{ () async throws(MyError) -> Void in ... }로 적으면for try await가MyError를 던지는 것으로 받아들여진다.concreteFunc: 함수의throws(MyError)도 마찬가지다.sum:S: AsyncSequence<Int, F>와F: Error로 “원소가Int이고 에러가F인 시퀀스” 를 받고, 그F를throws(F)로 그대로 내보낸다. primary associated type 이 있어서 쓸 수 있는 문법이다.neverSum:some AsyncSequence<Int, Never>로 “안 던지는 시퀀스만” 받는다.for await하나로 충분하고try가 필요 없다.streams:sum(quiet)는AsyncStream의Failure가Never라서try없이await만 붙여 부른다.sum(Throwing())은MyError를 던지니try await가 필요하고,streams자신의throws(MyError)로 그대로 넘어간다.
이 절의 결론은 이렇다. 함수나 closure 의 thrown type 을 적으면 for try await 는 시퀀스의 Failure 를 그대로 던진다. 적지 않은 closure 의 thrown type 은 6.4 에서 any Error 다.
some AsyncSequence 와 any AsyncSequence
primary associated type 은 구체 타입을 숨기는 두 문법을 열어 준다. some AsyncSequence<Int, Never>(opaque) 과 any AsyncSequence<String, any Error>(existential) 다. 아래는 둘을 같이 쓰는 파일이다.
Primary.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protocol Feed {
func updates() -> any AsyncSequence<String, any Error>
}
func evens() -> some AsyncSequence<Int, Never> {
AsyncStream<Int> { c in
for i in 0..<6 { c.yield(i) }
c.finish()
}
.filter { $0 % 2 == 0 }
}
func consume(_ feed: any Feed) async throws {
for try await line in feed.updates() {
print(line)
}
let mapped = feed.updates().map { $0.uppercased() }
_ = mapped
}
func useEvens() async {
for await x in evens() { print(x) }
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Primary.swift
1
2
3
4
5
6
7
8
9
10
Primary.swift:17:21: error: member 'map' cannot be used on value of type 'any AsyncSequence<String, any Error>'; consider using a generic constraint instead [#ExistentialMemberAccess]
15 | print(line)
16 | }
17 | let mapped = feed.updates().map { $0.uppercased() }
| `- error: member 'map' cannot be used on value of type 'any AsyncSequence<String, any Error>'; consider using a generic constraint instead [#ExistentialMemberAccess]
18 | _ = mapped
19 | }
[#ExistentialMemberAccess]: <https://docs.swift.org/compiler/documentation/diagnostics/existential-member-access-limitations>
[exit 1]
any AsyncSequence<String, any Error> 를 for try await 로 도는 줄과, .filter 결과를 some AsyncSequence<Int, Never> 로 돌려주는 evens() 는 통과한다. 막히는 것은 existential 값에 map 을 부르는 한 줄(17:21)이다. 이 에러는 세 언어 모드에서 모두 같다. existential 값의 member 는 반환 타입이 AsyncMapSequence<Self, Transformed> 처럼 Self 가 공변이 아닌 자리에 있으면 쓸 수 없다는 SE-0309 의 제한에 걸린다. 뒤의 OpenMap.swift 가 쓰는 우회는 SE-0352 의 암묵적 열기(implicit opening) 다.
피치 스레드에서 Kolos65 (#23, 2024-10-16) 가 바로 이 에러를 들고 왔다. 제안이 구현된 지금, 표준 라이브러리 AsyncSequence 연산자들이 opaque 반환 타입을 채택하는 걸 막는 게 무엇이냐는 질문이었다. map 이 Self 를 generic parameter 로 쓰는 AsyncMapSequence<Self, Transformed> 를 돌려주기 때문에 existential 에는 못 쓴다는 설명이다. 6.4 인터페이스의 map 은 이렇게 선언되어 있다.
1
2
// 496 줄
@preconcurrency @inlinable public __consuming func map<Transformed>(_ transform: @escaping @Sendable (Self.Element) async -> Transformed) -> _Concurrency::AsyncMapSequence<Self, Transformed>
반환 타입과는 별개로, FranzBusch (#4) 는 typed throws 를 위한 프로토콜과 컴파일러 변경만 들이고 표준 라이브러리 알고리즘에는 typed throws 를 아직 적용하지 않아도 문제가 없느냐고 물었고, hborla (#14) 는 알고리즘을 같이 바꿔도 이미 있을 문제 말고 떠오르는 것은 없다고 답했다. 다만 새 오버로드와 기존 오버로드가 함께 보이는 자리에서 overload resolution 에 미치는 영향은 따져야 하고, 새 오버로드도 Failure 의 availability 에 묶이게 된다고 했다.
그러면 existential 값에 map 을 쓰려면 어떻게 할까. 함수 인자를 some AsyncSequence<String, any Error> 로 받아 우회하는 코드를 썼다.
OpenMap.swift
1
2
3
4
5
6
7
8
9
func uppercased(_ s: some AsyncSequence<String, any Error>) -> some AsyncSequence<String, any Error> {
s.map { $0.uppercased() }
}
func consume(_ updates: any AsyncSequence<String, any Error>) async throws {
for try await line in uppercased(updates) {
print(line)
}
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift OpenMap.swift
1
[exit 0]
진단이 없다. uppercased(_:) 에 any AsyncSequence<String, any Error> 값을 넘기면 existential 이 열려서 some 인자로 들어가고, 그 안에서 map 을 부른다. 돌려주는 some AsyncSequence<String, any Error> 는 구체 타입을 숨긴다. BrentM (#24) 이 말한 eraseToAsyncSequence 같은 함수가 있다면 이 우회가 필요 없다는 이야기와 이어진다. 그런 함수는 이 제안에 들어 있지 않다.
표준 라이브러리의 채택
표준 라이브러리가 이 새 requirement 를 어떻게 따르는지 6.4 인터페이스에서 몇 군데 가져왔다.
AsyncStream.Iterator 는 next() 와 next(isolation:) 를 둘 다 구현한다.
1
2
3
4
5
6
7
8
9
10
11
// 829~837 줄
extension _Concurrency::AsyncStream : _Concurrency::AsyncSequence {
public struct Iterator : _Concurrency::AsyncIteratorProtocol {
public mutating func next() async -> Element?
// ... (생략)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
public mutating func next(isolation actor: isolated (any _Concurrency::Actor)?) async -> Element?
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@_implements(_Concurrency::AsyncIteratorProtocol, Failure) public typealias __AsyncIteratorProtocol_Failure = Swift::Never
}
}
앞에서 Motivation.swift 의 SIL 이 AsyncStream.Iterator.next(isolation:) 를 부르던 것이 이 구현이다. 표준 라이브러리 내부용인 @_implements attribute 로 Failure 를 Never 에 묶는다. 이름이 다른 typealias __AsyncIteratorProtocol_Failure 로 associated type 을 채우면 AsyncStream.Iterator.Failure 라는 새 public 멤버 이름을 만들지 않고 witness 만 지정할 수 있다. AsyncThrowingStream.Iterator 는 같은 모양에서 next(isolation:) 가 async throws(Failure) 이고 __AsyncIteratorProtocol_Failure = Failure 다(1434 줄).
위 인터페이스의 862 줄에는 extension _Concurrency::AsyncStream : @unchecked Swift::Sendable where Element : Swift::Sendable 가 있다. AsyncStream 은 원소가 Sendable 일 때만 Sendable 이고, Iterator 에 Sendable conformance 는 없다. pullInts 가 통과한 이유가 이 선언에 있다.
map, filter 같은 알고리즘의 iterator 도 next(isolation:) 를 구현하고, 받은 actor 를 안쪽 iterator 에 그대로 넘긴다. map 의 iterator 는 이렇다.
1
2
3
// 527~531 줄 근처
@inlinable public mutating func next(isolation actor: isolated (any _Concurrency::Actor)?) async throws(_Concurrency::AsyncMapSequence<Base, Transformed>.Failure) -> Transformed? {
guard let element = try await baseIterator.next(isolation: actor) else {
baseIterator.next(isolation: actor) 로 부른 쪽 isolation 을 그대로 넘긴다. 사슬로 이어진 map 과 filter 가 모두 같은 방식이라, for await 가 처음 넘긴 MainActor 가 사슬 끝까지 간다. AsyncFilterSequence 는 295 줄에서 같은 호출을 한다. 이 모양이 “자기 iterator 를 새 방식으로 옮길 때” 의 본보기가 된다.
TaskGroup 의 next 는 이 제안과 비슷한 방식을 쓰는데 모양이 조금 다르다.
1
2
3
4
// 3383, 3389 줄
@backDeployed(before: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0)
public mutating func next(isolation: isolated (any _Concurrency::Actor)? = #isolation) async -> ChildTaskResult?
@_disfavoredOverload public mutating func next() async -> ChildTaskResult?
TaskGroup 은 AsyncIteratorProtocol 의 requirement 가 아니라 자기 메서드라서 isolation 에 기본 인자 #isolation 을 붙일 수 있고, next() 는 @_disfavoredOverload 로 뒤로 밀려 있다. @backDeployed 라서 이전 OS 에서도 쓸 수 있다. ThrowingTaskGroup 은 3487 줄과 3491 줄에 같은 모양이 있다.
프로토콜 requirement 에는 기본 인자를 붙일 수 없다. 이 제약은 직접 확인했다.
DefaultArgReq.swift
1
2
3
protocol Puller {
mutating func pull(isolation: isolated (any Actor)? = #isolation) async -> Int?
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift DefaultArgReq.swift
1
2
3
4
5
6
7
DefaultArgReq.swift:2:12: error: default argument not permitted in a protocol method
1 | protocol Puller {
2 | mutating func pull(isolation: isolated (any Actor)? = #isolation) async -> Int?
| `- error: default argument not permitted in a protocol method
3 | }
4 |
[exit 1]
AsyncIteratorProtocol.next(isolation:) 가 인터페이스에서 기본 인자 없이 선언되어 있는 이유가 이것이다. 제안서의 Future directions 가 “protocol requirement 에 기본 인자를 붙이지 못하는 제약을 풀 수 있다면 #isolated 기본값을 달자” 고 적은 것도 같은 이야기다. 뒤의 “앞으로의 방향” 에서 다시 본다.
마지막으로 distributed actor 안에서의 for await 도 되는지 확인했다. ktoso (피치 #19) 가 (any Actor)? 로는 distributed actor 가 안 되니 (any AnyActor)? 로 해야 한다고 짚었기 때문이다.
Distributed.swift
1
2
3
4
5
6
7
8
9
10
11
import Distributed
distributed actor Reader {
typealias ActorSystem = LocalTestingDistributedActorSystem
func readAll(_ stream: AsyncStream<NonSendable>) async {
for await item in stream {
print(item.value)
}
}
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Distributed.swift
1
[exit 0]
세 언어 모드 모두 진단이 없다. SIL 을 열면 for await 가 DistributedActor.asLocalActor 로 얻은 any Actor 를 Optional<any Actor> 로 넘겨 AsyncStream.Iterator.next(isolation:) 를 부른다.
1
2
function_ref @(extension in Distributed):Distributed.DistributedActor.asLocalActor.getter : Swift.Actor
function_ref @Swift.AsyncStream.Iterator.next(isolation: isolated Swift.Actor?) async -> A?
asLocalActor 는 distributed actor 를 any Actor 로 바꿔 주는 getter 이고 [available 15.0] 이다. 제안이 파라미터 타입을 (any Actor)? 로 둔 채로도 distributed actor 안의 루프가 컴파일되는 것을 이 SIL 이 보여 준다. DistributedActor 는 다른 프로세스나 기기에 있는 actor 를 같은 문법으로 다루는 actor 이고, LocalTestingDistributedActorSystem 은 같은 프로세스 안에서 그 흐름을 시험하는 용도의 시스템이다.
기대 효과
여기까지 돌려 본 것을 한 표로 모은다. 모두 6.4 컴파일러(Xcode 27)로 측정한 값이고, 진단 열은 Swift 5 / Swift 5 + complete / Swift 6 순서다.
| 상황 | 측정 결과 |
|---|---|
@MainActor 안에서 AsyncStream<NonSendable> 를 for await (Motivation.swift) | 진단 0개 / 0개 / 0개 |
같은 자리에서 iterator 를 꺼내 next() 를 직접 호출 (ExplicitNext.swift) | 0개 / warning 2개 / error 2개 |
next() 만 구현한 iterator 의 실행 위치 (Where.swift) | thread=other 3번 |
next(isolation:) 를 구현한 iterator 의 실행 위치 (Where.swift) | thread=main actor=MainActor |
-Onone SIL 의 hop_to_executor 개수 (Hops.swift) | loopOld 3개, loopNew 2개 |
next() 만 구현한 타입 (OnlyNext.swift) | 진단 0개 / 0개 / 0개 |
둘 다 구현하지 않은 타입 (Neither.swift) | 세 모드 모두 does not conform error |
rethrows 로 쓴 containsValue (Rethrows.swift) | 진단 0개 / 0개 / 0개 |
throws(Failure) 로 쓴 containsValue (TypedContains.swift) | 진단 0개 / 0개 / 0개 |
any AsyncSequence<String, any Error> 에 map (Primary.swift) | 세 모드 모두 ExistentialMemberAccess error |
첫 줄과 둘째 줄의 차이가 이 제안의 요점이다. for await 는 컴파일러가 next(isolation:) 를 부르니까 NonSendable 원소도 @MainActor 안에서 돈다. 그런데 next() 를 손으로 부르면 Swift 6 모드에서 여전히 error 다. 새 requirement 는 컴파일러가 만든 호출을 고치는 것이지, 사람이 쓴 next() 호출을 풀어 주는 것이 아니다.
실행 위치와 hop 개수는 next(isolation:) 를 구현한 iterator 에서 줄었다. Where.swift 의 OldStyle 은 세 번 모두 main 이 아닌 thread 에서 돌았고, NewStyle 은 MainActor 에서 돌았다. 제안서의 “Implications on adoption” 이 말하는 “fewer hops to the generic executor” 가 이 출력으로 보이는 부분이다.
위 표의 OnlyNext 와 Neither 는 정반대 결과이고, 앞의 두 기본 구현 구조 그대로다.
다른 선택지는 왜 안 됐나
제안서 본문과 포럼 스레드에서 “이렇게 하면 안 되나” 로 나온 방법이 네 가지다. 각각 누가 묻고 누가 답했는지를 같이 적는다.
기존 next() 를 고치는 방법
가장 먼저 나오는 질문은 새 requirement 를 만들지 말고 next() 자체를 고치면 안 되느냐는 것이다. 리뷰 전 피치에서 wadetregaskis (#3) 가 “기존 메서드를 그 자리에서 업데이트할 방법은 정말 없느냐” 고 물었다. hborla (#8) 의 답은 이렇다. “There is no way to avoid adding a new entry point because the method needs to accept a new parameter, and the typed throws ABI (not just the mangling) is different from the throws/rethrows ABI.”
제안서의 ABI 절이 같은 이야기를 한다. next() 가 actor isolation 에 대해 일반적이 되려면 actor 를 parameter 로 받아야 한다. async 호출이 끝난 뒤 그 actor 로 돌아오는 hop 에 그 actor 가 필요하기 때문이다. 그리고 typed throws 의 ABI 는 rethrows 의 ABI 와 다르다. 그래서 새 requirement 가 필요하다는 것이 제안서의 입장이다. 기존 next() 를 두고 새 함수를 더하니, 기존 conformance 는 next() 만 구현한 채로 계속 컴파일된다. 이 글에서 본 OnlyNext 가 그 경우다.
같은 글에서 hborla 는 이름에도 열려 있다고 했다. “I’m absolutely open to alternative names for nextElement(). We could even just call it next() since it accepts a parameter and the original doesn’t.” 최종 이름은 next(isolation:) 로, 피치 때 이름 nextElement 에서 바뀌었다. 같은 이름을 쓰면 나중에 isolated 인자에 기본 인자가 생겼을 때 next() 호출이 새 쪽으로 풀려야 한다는 조건을 hborla 가 같이 적었다. 이 조건이 뒤에서 볼 기본 인자 이야기와 이어진다.
existential 이 아닌 isolation parameter
두 번째는 (any Actor)? 라는 existential 파라미터 타입이다. 제안서의 Alternatives 는 이 선택을 이렇게 설명한다. nil 이 nonisolated 를 나타내야 하는데, nonisolated 문맥을 나타내는 구체 Actor 타입은 없다. 그래서 some Actor 나 (some Actor)? 대신 (any Actor)? 를 쓴다. 대안은 두 가지로 적혀 있다.
nonisolated를nil이 아닌 다른 값으로 나타내거나, 표준 라이브러리에 구체적인 optional actor 타입을 가진 선언을 두는 방법. 컴파일러가 그 값을 isolation 검사 때 특별하게 알아야 한다.- 항상
nonisolated인 별도 entry point 를 두는 방법. 제안서는 isolation 에 대해 추상화하는 구현이 하나라는 목적이 사라진다고 쓴다.
제안서는 또 (any Actor)? 를 쓰기 때문에 embedded Swift 가 이 함수를 쓰려면 class existential 을 지원해야 한다고 적는다.
이 지점은 피치 스레드에서도 논의되었다. FranzBusch (#4) 는 embedded 에서 any Actor 때문에 AsyncSequence 사용이 제한되면 아쉽겠다고 물었고, hborla (#14) 는 any Actor 가 class-constrained existential 이고 actor 를 쓰는 embedded 코드는 어차피 allocating subset 안에 있어야 한다고 답했다. FranzBusch (#16) 는 actor 없이 AsyncSequence 만 쓰고 싶은 embedded 시스템이 있을 수 있는데 이 변경이 둘을 묶는다고 다시 짚었다.
Philippe_Hausler (#17) 는 두 방향으로 말했다. 동시성을 쓰는 embedded 시스템은 heap 할당을 할 만한 메모리가 있을 가능성이 크고, 참조 타입 existential(Actor 포함)을 추가하는 것이 type metadata 전체를 요구하지 않고 가능할 수 있다는 것이다. 그런 결정은 쉽게 내릴 일이 아니고 제안에서 미뤄도 된다고 했다. 대안으로는 some Actor 를 받는 메서드와 isolation 이 필요 없다는 것을 나타내는 인자를 받는 메서드를 둘 다 만드는 안을 말하면서, some Actor 오버로드와 짝이 되는 _ : Never? 오버로드를 두는 방법을 “hacky (but perhaps smart… I haven’t decided which one it is yet)” 라고 적었다. 제안서는 이 안을 따르지 않았다.
region 분석에 맡기는 방법
세 번째는 SE-0414 의 region 분석으로 풀자는 안이다. Jumhyn (#9) 은 region isolation 논의에서 next() 를 “parameter 와 결과를 generic context 와 합치지 않는 것” 으로 표시하는 해법이 거론된 기억이 있다며, 왜 이 방향을 택했느냐고 물었다. 새 방법이 불필요한 hop 을 피하는 것 말고 다른 이점도 있는지도 물었다.
hborla (#14) 의 답은 두 겹이다. 첫째, 그 방법은 iterator 가 disconnected region 에 있을 때만 통한다. “That generally will not be true for non-Sendable async sequences unless they’re created and used entirely locally.” 이 글 앞에서 localOnMain 은 막히고 build closure 를 @Sendable 로 떼어 낸 V.swift 는 통과한 것이 같은 이야기다. 둘째, 경고를 다 없애도 hop 이 많다는 문제가 남는다. 다른 actor 에 isolated 된 계산이라면 next() 는 generic executor 로 갔다가 바로 다른 executor 로 가야 한다. hborla 는 “isolating next() to the calling actor is the right default” 라고 적었다. 그러면서 원소를 만드는 closure 를 isolated 로 만들거나, next 에 isolated 인자를 명시하는 도구도 같이 남는다고 했다.
같은 글에서 region isolation 이 앞으로 AsyncSequence 에 쓸모가 있을 수 있다는 이야기도 한다. AsyncStream.Continuation.yield 로 non-Sendable 값을 몰래 넘길 수 있는데, yield 가 transferring 파라미터를 받게 하고 next 의 결과를 transferring 으로 하면 non-Sendable 원소의 시퀀스를 actor 안에서 돌 수 있다는 구상이다. 이 구상의 transferring 은 나중에 SE-0430 의 sending 으로 정리된 그 기능이다. 이 글의 Motivation 이 진단 없이 도는 것은 next(isolation:) 쪽 해법으로 풀렸기 때문이다.
region 대안과는 별개로, FranzBusch (#4) 는 이 제안 자체가 성능을 바꿀 수 있다는 점을 짚었다. SE-0338 에서 nonisolated 메서드를 generic executor 로 보낸 것이 MainActor 를 오래 붙잡는 일이 많아서였다는 맥락에서, 이 제안은 “현재 문맥의 isolation 에 붙는” 표준 라이브러리의 첫 메서드가 된다는 것이다. hborla 는 SE-0338 의 동기가 actor 를 풀어 주는 것만이 아니고 Sendable 검사도 있었다고 보충하고, 성능이 달라질 수 있다는 점을 제안서에 더 적을 만하다고 답했다. MainActor 안에서 AsyncSequence 를 돌 때는 불필요한 hop 이 없어져서 suspension 이 줄어도 오히려 빨라질 수 있다는 것이다. 성능 문제가 생기고 원본 시퀀스를 disconnected region 에 둘 수 있다면 nil 을 넘겨 generic executor 에서 돌릴 수 있다는 것도, hborla 가 isolated(caller) 같은 방식 대신 명시적 isolated 파라미터를 고른 이유로 적었다.
호출 자리의 label 과 기본 인자
네 번째는 호출 자리가 어떻게 읽히느냐다. FranzBusch (#4) 는 iterator.nextElement(nil) 에서 nil 이 무슨 뜻인지 코드만 봐서는 알 수 없다며 nextElement(isolatedTo actor: ...) 처럼 외부 label 을 붙이자고 했다. hborla (#14) 는 isolatedTo label 이 마음에 든다고 하면서, isolated parameter 를 받아 그 isolation 에만 쓰는 함수가 더 나올 테니 API 설계 지침이 필요하다는 데 동의했다. 최종 모양은 next(isolation actor: ...) 이고 호출 자리의 label 은 isolation: 이다.
mklbtz (#6) 의 질문은 위에서 봤다. isolated 인자에 = #isolation 기본 인자나 @inheritsIsolation 을 쓸 계획이 없느냐는 것이다. hborla (#8) 는 isolated parameter 일반화가 John McCall 의 isolation inheritance pitch 에서 직접 나왔다고 했다. 분리할 수 있고 이 제안의 구현이 리뷰에 가까웠기 때문이다. 나머지 isolation inheritance 를 이 제안에 넣을 계획은 없다고 했다. 이 글의 DefaultArgReq.swift 가 보여 준 대로, protocol requirement 에는 기본 인자가 붙지 않는다. 그래서 requirement 쪽에는 label 만 있고, 기본 인자는 TaskGroup.next(isolation:) 같은 일반 메서드에만 붙어 있다.
앞으로의 방향
제안서가 남긴 이야기와 스레드에서 갈래가 나뉜 이야기를 정리한다. 여기 적은 것은 모두 확정된 것이 아니라 논의된 방향이다.
next(isolation:) 의 기본 인자
제안서의 Future directions 는 하나다. 대부분의 next(isolation:) 호출은 둘러싼 문맥의 isolation 을 넘기니, protocol requirement 에 기본 인자를 붙일 수 없다는 제약이 풀리면 기본값으로 John McCall 의 pitch 에 나온 #isolated 를 달자는 것이다. 이 글의 DefaultArgReq.swift 가 default argument not permitted in a protocol method 로 막힌다는 것을 보여 줬다. 현재 for await 는 컴파일러가 #isolation 에 해당하는 값을 직접 넘겨서 이 제약과 상관없이 돈다.
noncopyable 원소
Karl (#12) 은 이 타입들을 곧 크게 고쳐야 한다고 짚었다. noncopyable 이나 non-escaping 원소를 지원하려면 next() 는 원소를 돌려줄 수 없고 호출한 쪽이 원소를 빌려 보게(borrow) 해야 한다는 것이다. 지금 언어에서는 closure 로 표현할 수 있다며 개략적인 예를 적었다. 그 예에서 next 는 (Element) async throws(T) -> IterationResult 형태의 yield closure 를 받고, 에러 타입은 Failure 와 T 의 합집합이다. 위 isolation 파라미터도 그 안에 들어가야 한다고 썼다. 이 제안이 만든 next(isolation:) 의 모양이 나중에 다시 바뀔 수 있다는 한 사람의 지적이다.
back-deploy
가장 많이 논의된 방향은 이전 OS 에서 쓰는 것이다. KeithBauerANZ (#11) 는 back-deploy 가 가장 걱정이라고 썼다. iOS 18 이 필요하다면 쓸 수 있기까지 3년 이상 걸리고, Combine 에 그만큼 더 머물러야 한다는 것이다. hborla (#14) 의 답은 이랬다. “None of us are happy with the back deployment restrictions in the proposal, but we have not come up with a solution that’s actually feasible.” primary associated type 을 쓸 방법을 찾더라도 쓸 수 있는 것이 제한되고, 예로 any AsyncSequence<T, Never> 로 dynamic cast 는 못 한다고 했다.
DevAndArtist (#15) 는 existential 로 cast 하는 일이 알고리즘을 복잡한 체인으로 감싸는 일보다 필요가 크지 않을 것 같다며 back deployment 탐색에 한 표를 더했다. KeithBauerANZ (#18) 는 자신이 원하는 것을 세 가지로 정리했다. 요구사항이 any AsyncSequence<T, E> 를 돌려주는 프로토콜을 쓰고, 그 existential 을 순회하거나 map 같은 변환을 하고, 입력 시퀀스가 던지는지에 따라 조건부로 던지는 새 시퀀스를 만드는 것이다. 그러면서 existential 을 여는 연산이 dynamic cast 와 같은 것이라면 불가능한 쪽인지 모르겠다고 덧붙였다.
리뷰와 수락 스레드에서도 이 질문이 이어진다. 리뷰 스레드에서 dmt (#2) 는 _Concurrency 에 선언된 프로토콜이니 BackDeploymentConcurrency 로 @available 을 없앨 수 있지 않느냐고 물었다. 수락 공지 스레드에서도 dmt (#2) 가 backport 를 하지 않기로 했느냐고 물었다. Jumhyn (#3) 은 backport 여부는 evolution review 나 Language Steering Group 의 결정 권한 밖이고, 배포 계획을 아는 Apple 쪽 사람이 답해야 한다고 했다. 그래서 이 글의 OldTarget.swift 와 Primary.swift 가 macOS 14 에서 낸 에러가 지금의 상태다.
Swift 6 모드와 마이그레이션
이 제안을 받아 코드를 옮길 때 보는 변경점을 표로 모은다. 모든 칸은 6.4 컴파일러로 측정한 것이다.
| 하던 일 | 6.4 에서 |
|---|---|
for await 로 non-Sendable 원소의 AsyncStream 을 @MainActor 에서 순회 | 세 모드 모두 진단 없음 |
non-Sendable 원소의 iterator.next() 를 @MainActor 에서 직접 호출 | Swift 5 진단 없음, 5 + complete warning, Swift 6 error |
next() 만 구현한 iterator | 진단 없음. 실행은 generic executor 에서 |
next(isolation:) 만 구현한 iterator, 배포 대상 macOS 14 | requires 'next()' to be available in macOS 14 and newer error |
next(isolation:) 만 구현한 iterator, 기본 배포 대상 | 진단 없음 |
| 둘 다 구현하지 않은 iterator | does not conform error. Failure 를 typealias 하면 컴파일되고 실행하면 무한 루프 |
any AsyncSequence<..> 값에 map 호출 | error. some AsyncSequence 인자를 받는 함수를 거치면 통과 |
macOS 14 에서 any AsyncSequence<String, any Error> | 'Failure' is only available in macOS 15.0 or newer error |
async rethrows 로 쓴 확장 | Swift 5 와 Swift 6 모드 모두 진단 없음 |
async throws(Failure) 로 쓴 확장 | 세 모드 모두 진단 없음 |
마지막 두 줄은 같은 함수를 다른 모양으로 쓴 것이다.
Rethrows.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
extension AsyncSequence {
func containsValue(_ value: Element) async rethrows -> Bool where Element: Hashable {
for try await element in self {
if element == value { return true }
}
return false
}
}
func use() async {
let s = AsyncStream<Int> { $0.yield(1); $0.finish() }
let found = await s.containsValue(1)
print(found)
}
func useThrowing() async throws {
let s = AsyncThrowingStream<Int, any Error> { $0.yield(1); $0.finish() }
let found = try await s.containsValue(1)
print(found)
}
TypedContains.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension AsyncSequence {
func containsValue(_ value: Element) async throws(Failure) -> Bool where Element: Hashable {
for try await element in self {
if element == value { return true }
}
return false
}
}
func use() async {
let s = AsyncStream<Int> { $0.yield(1); $0.finish() }
let found = await s.containsValue(1)
print(found)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Rethrows.swift
1
[exit 0]
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift TypedContains.swift
1
[exit 0]
Rethrows.swift 의 async rethrows 확장은 AsyncSequence 가 rethrows 검사에 쓰이던 시절에 쓰던 모양이다. 6.4 에서 이 async rethrows 확장은 Swift 5 와 Swift 6 모드 모두에서 진단 없이 컴파일된다. TypedContains.swift 는 같은 함수를 throws(Failure) 로 쓴 것이고, use() 의 AsyncStream 은 Failure 가 Never 라서 try 없이 부른다. 앞으로 새로 쓰는 확장은 throws(Failure) 쪽이 Never 도 담을 수 있어 낫다. @rethrows 프로토콜 자체는 앞에서 본 Douglas_Gregor (리뷰 #8) 의 답대로 정리될 예정이다.
정리
이 제안은 AsyncSequence 와 AsyncIteratorProtocol 에 두 가지를 더한다. 하나는 Failure 연관 타입과 primary associated type 이고, 다른 하나는 호출한 쪽의 actor 를 받는 next(isolation:) 다. 앞의 것이 @rethrows 를 대신해서 “던지느냐” 를 타입으로 나타내고, 뒤의 것이 actor 안에서 도는 for await 의 Sendable 진단과 불필요한 executor hop 을 한꺼번에 줄인다.
이 글에서 측정한 것은 이렇다.
for await는next(isolation: #isolation)으로 컴파일되어,@MainActor안의 non-Sendable 원소 순회가 세 모드 모두 진단 없이 돈다.next()를 손으로 부르는 코드는 Swift 6 모드에서 여전히 error 이고,next(isolation:)를 구현한 iterator 만MainActor에서 돈다.- 두 기본 구현은 서로를 부르며, 둘 다 구현하지 않으면
typealias Failure만으로 컴파일되고 무한 루프를 돈다. 이 경우를 막는 규칙은 deprecated 와 unavailable 기본 구현에 대해서 동작하고, 6.4 의next(isolation:)기본 구현 자체는 이 규칙의 대상이 아니다. - 배포 대상이 macOS 15 미만이면
Failure와 primary associated type 을 쓰는 자리, 그리고 기본next()에 기대는next(isolation:)만 구현한 타입이 모두 availability error 가 된다. - primary associated type 으로
some과any를 쓸 수 있게 되었지만, 표준 라이브러리 알고리즘의 반환 타입은 바뀌지 않아서any값에map을 쓰려면some인자를 받는 함수를 거쳐야 한다.
피치에서 리뷰와 수락까지 스레드를 따라가 보면, 이 제안의 선택지는 대부분 “ABI 상 새 requirement 가 필요하다”, “region 분석만으로는 hop 이 안 줄어든다”, “nonisolated 를 나타낼 구체 actor 타입이 없다” 는 세 이유로 정리된다. back-deploy 는 가장 아쉬움이 컸던 부분이고, 이 글 시점에서 next() 만 구현한 기존 타입은 그대로 돌고 새 기능은 macOS 15 이상에서 쓴다.
관련 글
- [SE-0337] Incremental migration to concurrency checking
- [SE-0412] Strict concurrency for global variables
- [SE-0414] Region based Isolation
- [SE-0420] Inheritance of actor isolation
- [SE-0423] Dynamic actor isolation enforcement from non-strict-concurrency contexts
- [SE-0430] sending parameter and result values
- [SE-0431] @isolated(any) Function Types
- [SE-0434] Usability of global-actor-isolated types
- [SE-0461] Run nonisolated async functions on the caller’s actor by default

