포스트

[SE-0468] Hashable conformance for Async(Throwing)Stream.Continuation

이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.


제안서 정보


한 줄 요약

AsyncStream.Continuation 과 AsyncThrowingStream.Continuation 이 Hashable 이 되었다. 같은 stream 에서 나온 continuation 은 몇 번을 복사해도 서로 같고 hash 값도 같다. 다른 stream 의 continuation 은 같지 않다. 그래서 구독자마다 stream 을 하나씩 내주는 Observer 패턴에서 continuation 을 Set 에 넣고, onTermination 에서 그 continuation 을 지울 수 있다. 이 글은 “같다” 가 정확히 언제까지 유지되는지, 이 conformance 가 없던 때의 우회가 어땠는지, 배포 대상이 낮으면 어디서 막히는지를 컴파일해서 실행한 출력으로 정리한다.


어떤 문제였나

SE-0468 은 타입 하나에 Hashable 을 붙이는 작은 제안서다. 이 작은 변경이 풀어 주는 불편이 무엇인지 보려면, 먼저 AsyncStream 으로 여러 구독자를 받는 코드가 어떤 모양인지 알아야 한다.

이 글의 순서는 이렇다. 먼저 AsyncStream 과 continuation 이 무엇인지 짚고, 제안서가 든 Observer 패턴을 컴파일해 본다. 그다음 누가 누구인지 알아볼 방법이 없다는 문제가 어디서 생기는지, 이 conformance 가 없던 때의 우회 두 가지가 어땠는지 본다. 바뀌는 것은 “같다” 의 기준, 상태가 바뀌어도 유지되는 동등성, throwing 판, 실제로 구독자가 들고 나는 실행, 버려진 stream, 그리고 Identifiable 이 아니라는 점의 순서로 측정한다.


AsyncStream 과 continuation 이란?

AsyncStream 은 값이 시간에 따라 하나씩 도착하는 흐름을 for await 로 읽게 해 주는 타입이다. 우체통에 비유할 수 있다. 우체통 앞에서 편지가 올 때마다 하나씩 꺼내 읽고, 우체통이 닫히면 읽기를 마치는 쪽이 AsyncStream 이다.

편지를 넣는 쪽이 AsyncStream.Continuation 이다. 우체통의 투입구에 해당한다. yield 로 값을 넣고, finish 로 우체통을 닫는다. Continuation 은 Sendable 이어서 다른 task 나 다른 스레드에서 들고 있어도 된다. 이 글에서 중요한 성질이 하나 더 있다. Continuation 은 class 가 아니라 struct 다. 컴파일된 SDK 의 인터페이스에 public struct Continuation : Sendable 이라고 적혀 있다. 변수에 담아 둔 투입구를 let copy = c1 로 복사하면 값이 복사되고, 그 값 안에 들어 있는 stream 내부 저장소로의 참조도 같이 복사된다. 복사본으로 yield 해도 같은 stream 에 값이 들어간다.

stream 과 continuation 을 만드는 방법은 두 가지다. 클로저를 받는 초기화 함수 AsyncStream(_:bufferingPolicy:_:) 는 클로저에 continuation 을 넘겨 준다. 그 클로저 안에서 continuation 을 바깥에 저장하거나 바로 쓴다. 두 값을 한 번에 돌려주는 makeStream 도 있다. makeStream 은 내부에서 같은 초기화 함수를 부르는 얇은 함수다.

1
2
읽는 쪽: for await value in stream { ... }
넣는 쪽: continuation.yield(value) ... continuation.finish()

끝나는 때를 알려 주는 것이 onTermination 이다. continuation 의 속성이고, stream 이 끝나면 불리는 클로저를 넣는다. 인자는 끝난 이유인 Termination 이고 finished(넣는 쪽이 finish() 를 불렀다) 와 cancelled(읽는 쪽이 취소했거나 읽기를 그만뒀다) 두 값이 있다. 인터페이스에서 이 속성은 nonmutating set 이다. continuation 값 자체가 아니라 공유 저장소에 클로저를 넣는다는 뜻이고, 아래에서 “상태가 바뀌어도 같다” 를 읽을 때 이 점이 쓰인다.


구독자마다 stream 을 내주는 Observer

값 하나가 바뀔 때마다 여러 곳에 알려 주고 싶을 때, AsyncStream 을 쌓아 올린 Observer 가 있다. 제안서의 예제는 이렇다. 구독자 한 명이 values 를 부를 때마다 새 AsyncStream 을 만들어 돌려주고, 그 stream 의 continuation 을 Sender 가 모아 둔다. value 가 바뀌면 모아 둔 모든 continuation 에 yield 한다. 구독자가 읽기를 그만두면 그 continuation 을 모음에서 지워야 한다. 지우지 않으면 모음이 끝없이 자라고, 이미 끝난 stream 에 계속 yield 하게 된다.

이 예제를 samples 에 그대로 옮겨서 Swift 6 모드로 컴파일했다.

Sender.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
import Foundation

@MainActor private class Sender {
    var value: Int = 0 {
        didSet {
            for c in continuations {
                c.yield(value)
            }
        }
    }

    var values: some AsyncSequence<Int, Never> {
        AsyncStream<Int>(bufferingPolicy: .bufferingNewest(1)) { continuation in
            continuation.yield(value)
            self.continuations.insert(continuation)
            continuation.onTermination = { _ in
                DispatchQueue.main.async {
                    self.continuations.remove(continuation)
                }
            }
        }
    }

    private var continuations: Set<AsyncStream<Int>.Continuation> = []
}
@main struct M { static func main() {} }
1
bash diag.sh Sender.swift
1
[exit 0]

진단이 없다. 이 글의 diag.sh 는 -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 으로 컴파일하는 스크립트다. -emit-sil 은 타입 검사 뒤 SIL(컴파일러 중간 표현) 단계까지 가서 그 단계의 진단까지 내고, -parse-as-library 는 최상위 코드가 없는 소스 파일로 다루라는 옵션이고, -wmo 는 모든 파일을 한 모듈로 같이 컴파일하게 한다. 컴파일러는 Apple Swift version 6.4 (swiftlang-6.4.0.34.1) 이다. Swift 5 모드와 Swift 5 의 -strict-concurrency=complete 에서도 같은 파일은 진단이 없었다.

AsyncStream 초기화와 onTermination 으로 구독자 stream 만들기

AsyncStream.init(_:bufferingPolicy:_:) 는 클로저를 받아서 stream 을 만든다. 이 코드의 클로저는 continuation 으로 첫 값을 바로 yield 하고, Sender 가 들고 있는 Set 에 넣고, onTermination 에 지우는 코드를 건다. bufferingPolicy: .bufferingNewest(1) 은 읽는 쪽이 따라가지 못할 때 가장 최근 값 하나만 남기라는 뜻이다. yield 는 값을 stream 에 넣는 메서드이고, 이 stream 이 이미 끝났으면 값을 버린다.

Set 은 같은 값을 두 번 담지 않는 집합이다. insert 로 넣고 remove 로 뺀다. 원소가 Hashable 이어야 한다. Hashable 은 두 값이 같은지(==) 와 같은 값이 같은 hash 값을 내는지(hash(into:)) 를 정하는 프로토콜이다. Set 은 hash 값으로 원소를 찾아가고 == 로 최종 확인한다. onTermination 안의 DispatchQueue.main.async 는 main queue 에 일을 하나 넣는 호출이다. Sender 는 @MainActor 라서 continuations 를 main actor 에서만 만져야 하고, onTermination 은 @Sendable 클로저라서 어디서 불릴지 모르니 main 으로 넘겨서 지운다.

이 코드가 6.4 에서 컴파일되는 것은 AsyncStream<Int>.Continuation 이 Hashable 이어서 Set<AsyncStream<Int>.Continuation> 이 성립하기 때문이다. SE-0468 이 없던 때는 이 한 줄이 오류였다.


알아볼 방법이 없던 continuation

SE-0468 이전에는 Set<AsyncStream<Int>.Continuation> 이 성립하지 않았고 Dictionary 의 키로도 쓸 수 없었다. 구독자가 끝났을 때 “그 구독자의 continuation 이 모음의 어느 것인가” 를 알려 줄 방법이 continuation 에 없었기 때문이다. 제안서 Motivation 은 이렇게 요약한다. onTermination 에서 해당 continuation 을 지우려면 continuation 을 비교할 수 있어야 한다. 구독자마다 조회 키를 붙여 두는 것도 가능하지만 비효율적이다.

직접 정체성을 꺼내 쓰면 되지 않을까 싶지만 길이 없다. Continuation 은 struct 라서 class 의 정체성을 비교하는 === 를 쓸 수 없고, 정체성을 hash 값으로 만들어 주는 ObjectIdentifier 도 class 인스턴스만 받는다. 직접 물어봤다.

ObjectId.swift

1
2
3
4
5
func f() {
  let (_, c) = AsyncStream<Int>.makeStream()
  print(ObjectIdentifier(c))
}
@main struct M { static func main() { f() } }
1
bash diag.sh ObjectId.swift
1
2
3
4
5
6
7
8
ObjectId.swift:3:26: error: argument type 'AsyncStream<Int>.Continuation' expected to be an instance of a class or class-constrained type
1 | func f() {
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   print(ObjectIdentifier(c))
  |                          `- error: argument type 'AsyncStream<Int>.Continuation' expected to be an instance of a class or class-constrained type
4 | }
5 | @main struct M { static func main() { f() } }
[exit 1]

ObjectIdentifier 는 class 나 class 로 제한된 타입의 인스턴스만 받는다. continuation 에서 정체성을 꺼낼 길이 바깥에는 없고, stream 내부 저장소가 정체성을 쥐고 있는데 그것이 밖으로 나오지 않는다. 제안서가 구현 아이디어로 든 것이 바로 이 지점이다. continuation 은 이미 내부에 AsyncStream._Storage 참조를 갖고 있고(아래 Layout.swift 에서 확인한다), 그 참조의 정체성으로 Hashable 을 쉽고 효율적으로 만들 수 있다는 것이다.

우회 하나, class 상자에 넣기

제안서가 보여 주는 6.2 이전의 길은 continuation 을 class 로 감싸고 그 상자의 정체성을 쓰는 것이다.

Box.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
import Foundation

@MainActor private class Sender {
    var value: Int = 0 {
        didSet {
            for c in continuations {
                c.value.yield(value)
            }
        }
    }

    var values: some AsyncSequence<Int, Never> {
        AsyncStream<Int> { (continuation: AsyncStream<Int>.Continuation) -> Void in
            continuation.yield(value)
            let box = ContinuationBox(value: continuation)
            self.continuations.insert(box)
            continuation.onTermination = { _ in
                DispatchQueue.main.async {
                    self.continuations.remove(box)
                }
            }
        }
    }

    private var continuations: Set<ContinuationBox> = []

    private final class ContinuationBox: Hashable, Sendable {
        let value: AsyncStream<Int>.Continuation

        init(value: AsyncStream<Int>.Continuation) {
            self.value = value
        }

        static func == (lhs: Sender.ContinuationBox, rhs: Sender.ContinuationBox) -> Bool {
            lhs === rhs
        }

        func hash(into hasher: inout Hasher) {
            hasher.combine(ObjectIdentifier(self))
        }
    }
}
@main struct M { static func main() {} }
1
bash diag.sh Box.swift
1
[exit 0]

ContinuationBox 는 final class 이고 == 는 ===, hash 는 ObjectIdentifier(self) 다. continuations 에는 상자를 넣고, onTermination 에서도 같은 상자를 캡처해서 지운다. 구독자 한 명마다 class 인스턴스 하나(heap 할당)가 늘고, Hashable 상용구 열 줄이 따라온다. value.yield 처럼 모든 사용처에서 상자를 한 겹 벗기는 것도 번거롭다. 같은 코드가 -target arm64-apple-macos15 에서도 진단이 없다는 점은 뒤에서 본다.

우회 둘, 번호를 붙여 Dictionary 에 넣기

pitch 스레드에서 olbo 가 낸 다른 우회는 stream 을 만들 때마다 번호를 매기고 [UInt: Continuation] 으로 들고 있는 것이다. 이 방식을 이 글의 Observer 에 넣어 옮겼다. values 의 반환 타입을 AsyncStream<Int> 로 적고 Sender 를 final class 로 바꿨으며, main 은 뒤의 Observer.swift 와 같다.

Counter.swift 의 바뀐 부분

1
2
3
4
5
6
7
8
9
10
  private(set) var count: UInt = 0
  ...
      let id = count + 1
      count = id
      continuations[id] = continuation
      continuation.onTermination = { _ in
        Task { self.continuations.removeValue(forKey: id) }
      }
  ...
  private var continuations: [UInt: AsyncStream<Int>.Continuation] = [:]
1
bash diag.sh Counter.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Counter.swift:15:21: error: main actor-isolated property 'continuations' can not be mutated from a nonisolated context
13 |       continuations[id] = continuation
14 |       continuation.onTermination = { _ in
15 |         Task { self.continuations.removeValue(forKey: id) }
   |                     |- error: main actor-isolated property 'continuations' can not be mutated from a nonisolated context
   |                     `- note: consider declaring an isolated method on 'MainActor' to perform the mutation
16 |       }
17 |     }
18 |   }
19 |   var subscriberCount: Int { continuations.count }
20 |   private var continuations: [UInt: AsyncStream<Int>.Continuation] = [:]
   |               `- note: mutation of this property is only permitted within the actor
21 | }
22 | 
[exit 1]

onTermination 안의 Task { ... } 는 actor 를 물려받지 못해서, @MainActor 클래스의 continuations 를 고치는 이 코드는 Swift 5 모드와 Swift 6 모드 모두 위의 오류가 난다. 그래서 Task { @MainActor in ... } 로 격리를 적었고, 이렇게 하면 컴파일되고 돈다(CounterFixed.swift). 이 우회의 비용은 상자와 다른 곳에 있다. 번호를 세는 count 와 번호로 찾는 Dictionary 를 Sender 가 따로 들고 있어야 하고, 지우는 일이 새 Task 를 하나 만드는 일이 된다.


무엇이 바뀌나

바뀐 것은 한 가지다. AsyncStream.Continuation 과 AsyncThrowingStream.Continuation 이 Hashable 이다. 아래에서는 SDK 에 들어온 선언을 먼저 보고, “같다” 가 무엇을 뜻하는지를 여러 상황에서 잰 다음, 제안서의 Observer 를 실제로 돌려서 구독자가 들고 나는 것을 본다.


SDK 에 선언된 모양

Xcode 27 SDK 의 _Concurrency swiftinterface 에서 선언을 찾았다.

1
2
3
4
5
6
7
8
9
10
11
@available(anyAppleOS 26.0, *)
extension _Concurrency::AsyncStream._Concurrency::Continuation : Swift::Hashable {
  @available(anyAppleOS 26.0, *)
  public func hash(into hasher: inout Swift::Hasher)
  @available(anyAppleOS 26.0, *)
  public var hashValue: Swift::Int {
    get
  }
  @available(anyAppleOS 26.0, *)
  public static func == (lhs: _Concurrency::AsyncStream<Element>._Concurrency::Continuation, rhs: _Concurrency::AsyncStream<Element>._Concurrency::Continuation) -> Swift::Bool
}

AsyncThrowingStream.Continuation 도 같은 모양이고 == 의 인자만 AsyncThrowingStream<Element, Failure>.Continuation 이다. 이 선언에서 볼 것은 세 가지다.

  • ==, hash(into:), hashValue 가 함께 선언된다. Equatable 은 Hashable 에 포함되어 같이 들어온다
  • where 절이 없다. Element 가 Hashable 일 필요가 없다. struct Plain {} 처럼 Hashable 도 Equatable 도 아닌 원소 타입의 AsyncStream<Plain>.Continuation 두 개와 복사본을 Set 에 넣으면 set count: 2 가 나온다(NonHashableElement.swift, [exit 0])
  • 전부 anyAppleOS 26.0 이다. Swift 6.2 구현이 OS 26 과 함께 나온 것과 맞는다. back-deploy 표시가 없다는 점은 아래 마이그레이션 절에서 컴파일로 본다

stream 단위의 동등성

제안서 Detailed design 은 네 문장이다. init 의 build 클로저가 불릴 때마다 다른 continuation 을 받는다. 같은 continuation 의 모든 복사본은 같다. 값이나 에러를 yield 하거나 stream 을 끝내거나 순회를 취소해도 동등성이 바뀌지 않는다. onTermination 을 넣어도 바뀌지 않는다. 이 네 문장을 하나씩 코드로 쟀다. 앞의 세 문장은 Equality.swift 가, 순회 취소와 에러로 끝내기는 CancelEq.swift 가 맡는다.

Equality.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
@main struct M {
  static func main() async {
    var captured: AsyncStream<Int>.Continuation?
    let s1 = AsyncStream<Int> { c in captured = c }
    let c1 = captured!
    let copy = c1
    let (s2, c2) = AsyncStream<Int>.makeStream()
    print("copy == c1:", copy == c1, "hash equal:", copy.hashValue == c1.hashValue)
    print("c1 == c2:", c1 == c2)
    c1.onTermination = { _ in }
    c1.yield(1)
    print("after onTermination+yield:", copy == c1)
    c1.finish()
    print("after finish:", copy == c1)
    var it = s1.makeAsyncIterator()
    print("iterate:", await it.next() as Any, await it.next() as Any)
    print("after iteration ended:", copy == c1)
    let set: Set = [c1, copy, c2]
    print("set count:", set.count)
    let (_, t1) = AsyncThrowingStream<Int, any Error>.makeStream()
    let t1b = t1
    let (_, t2) = AsyncThrowingStream<Int, any Error>.makeStream()
    print("throwing copy == :", t1 == t1b, "dict:", [t1: "a"][t1b] ?? "nil")
    _ = (s2, t2)
  }
}
1
bash diag.sh Equality.swift
1
[exit 0]
1
2
xcrun swiftc -parse-as-library -swift-version 6 Equality.swift -o eq
./eq
1
2
3
4
5
6
7
8
copy == c1: true hash equal: true
c1 == c2: false
after onTermination+yield: true
after finish: true
iterate: Optional(1) nil
after iteration ended: true
set count: 2
throwing copy == : true dict: a

복사본과 hashValue 로 같음 확인하기

c1 은 클로저 초기화로 얻은 continuation 이고 copy 는 그 복사본이다. c2 는 makeStream() 으로 따로 만든 stream 의 continuation 이다. hashValue 는 Hashable 이 주는 속성으로 hash 값을 Int 로 돌려준다. 첫 줄에서 복사본은 원본과 == 이고 hash 도 같다. 둘째 줄에서 다른 stream 의 c2 는 같지 않다. 이 두 줄이 Set 이 성립하는 조건이다. 같은 값은 같은 hash 를 내야 하고, 다른 stream 이면 == 가 거짓이어야 한다. hash 는 충돌해도 되지만(다른 값이 같은 hash 를 낼 수 있다), == 가 최종 판정이다.

같은 stream 의 continuation 은 복사해도 같은 원소라서, onTermination 클로저가 붙잡은 복사본으로 구독자 Set 에서 원본 c1 을 지울 수 있고 다른 stream 의 c2 는 지워지지 않는다

그림은 이 두 줄이 Observer 에서 하는 일이다. Set 에는 구독자 A 의 원본 c1 과 구독자 B 의 c2 가 들어 있고, A 의 onTermination 클로저가 붙잡은 것은 c1 의 복사본이다. 복사본으로 remove 하면 == 와 hash 가 같아서 c1 이 빠지고, c2 는 다른 stream 이라 그대로 남는다.

상태가 바뀌어도 같음 확인하기

세 번째 줄부터는 제안서의 “영향을 주지 않는다” 를 상황별로 본 것이다.

  • onTermination 을 넣고 yield(1) 한 뒤에도 copy == c1 이다. MemoryLayout 과 Mirror 로 보면 이유가 보인다(아래 Layout.swift). 저장 속성은 _Storage 참조 하나뿐이고, onTermination 은 그 저장소 안을 바꾸는 nonmutating set 이라 비교 대상인 참조는 그대로다
  • finish() 로 stream 을 끝낸 뒤에도 같다. 끝난 continuation 도 Set 에서 자기 자리를 찾을 수 있다. 이 성질이 없으면 onTermination 에서 지울 때 이미 끝난 continuation 을 못 찾는다
  • makeAsyncIterator() 로 iterator 를 만들고 next() 를 끝까지 부른 뒤(Optional(1) 다음 nil)에도 같다. makeAsyncIterator() 는 for await 가 내부에서 쓰는 iterator 를 직접 꺼낸다. 순회가 다 끝나 stream 이 비어도 동등성은 그대로다

그다음 Set([c1, copy, c2]) 의 count 가 2 다. c1 과 copy 가 한 원소로 합쳐지고 c2 가 하나 더 있다. 마지막 줄은 throwing 판이다. AsyncThrowingStream<Int, any Error>.makeStream() 의 continuation t1 과 복사본 t1b 가 같고, [t1: "a"][t1b] 로 Dictionary 를 복사본으로 조회하면 a 가 나온다. Set 의 원소만이 아니라 Dictionary 의 키로도 쓰이니, continuation 마다 값을 붙여 두는 쓰임까지 열렸다.

CancelEq.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@main struct M {
  static func main() async {
    var captured: AsyncStream<Int>.Continuation?
    let s = AsyncStream<Int> { c in captured = c }
    let c1 = captured!
    let copy = c1
    let t = Task { for await _ in s {} ; return "loop ended" }
    try? await Task.sleep(for: .milliseconds(20))
    t.cancel()
    print(await t.value)
    print("after cancel:", copy == c1, copy.hashValue == c1.hashValue)
    let (_, tc) = AsyncThrowingStream<Int, any Error>.makeStream()
    let tcopy = tc
    struct E: Error {}
    tc.finish(throwing: E())
    print("throwing after finish(throwing:):", tc == tcopy)
  }
}
1
2
3
loop ended
after cancel: true true
throwing after finish(throwing:): true

순회하던 task 를 취소해 for await 가 끝난 뒤에도 copy == c1 이고 hash 도 같다. throwing 판에서 finish(throwing:) 으로 에러를 담아 끝낸 뒤에도 복사본과 같다. 네 문장을 모두 쟀다.

Layout.swift

1
2
3
4
5
6
7
8
9
@main struct M {
  static func main() {
    print("size:", MemoryLayout<AsyncStream<Int>.Continuation>.size,
          "throwing size:", MemoryLayout<AsyncThrowingStream<Int, any Error>.Continuation>.size)
    let (_, c) = AsyncStream<Int>.makeStream()
    let m = Mirror(reflecting: c)
    for ch in m.children { print(ch.label ?? "-", type(of: ch.value)) }
  }
}
1
2
size: 8 throwing size: 8
storage _Storage

크기는 포인터 하나인 8바이트이고 저장 속성은 _Storage 참조 하나뿐이다. throwing 판도 8바이트다. 앞에서 말한 “내부 저장소 참조” 가 이 출력이다.

SE-0417 의 UnownedTaskExecutor 에 Hashable 을 붙인 SE-0523 도 키로 쓰고 싶다는 같은 동기에서 나왔다. UnownedTaskExecutor 는 == 는 이미 있었고 hash 만 없어서, 모아 둔 것에서 찾으려면 선형 탐색을 해야 했다.


throwing 판과 typed failure

AsyncThrowingStream 은 읽는 쪽에서 에러를 던질 수 있는 stream 이다. Hashable 은 같은 모양으로 붙었다. 한 가지 궁금증이 있었다. SE-0421 이후로 AsyncSequence 는 typed throws 를 지원하는데, AsyncThrowingStream<Int, MyError> 로 Failure 를 구체 타입으로 만들 수 있는지다.

TypedFailure.swift

1
2
3
4
5
6
7
struct E: Error {}
@main struct M {
  static func main() {
    let (_, t1) = AsyncThrowingStream<Int, E>.makeStream(of: Int.self, throwing: E.self)
    _ = t1
  }
}
1
bash diag.sh TypedFailure.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
TypedFailure.swift:4:47: error: static method 'makeStream(of:throwing:bufferingPolicy:)' requires the types 'E' and 'any Error' be equivalent
2 | @main struct M {
3 |   static func main() {
4 |     let (_, t1) = AsyncThrowingStream<Int, E>.makeStream(of: Int.self, throwing: E.self)
  |                                               `- error: static method 'makeStream(of:throwing:bufferingPolicy:)' requires the types 'E' and 'any Error' be equivalent
5 |     _ = t1
6 |   }

_Concurrency.AsyncThrowingStream.makeStream:4:22: note: where 'Failure' = 'E'
2 | @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
3 |   @backDeployed(before: macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0)
4 |   public static func makeStream(of elementType: Element.Type = Element.self, throwing failureType: Failure.Type = Failure.self, bufferingPolicy limit: AsyncThrowingStream<Element, Failure>.Continuation.BufferingPolicy = .unbounded) -> (stream: AsyncThrowingStream<Element, Failure>, continuation: AsyncThrowingStream<Element, Failure>.Continuation) where Failure == any Error}
  |                      `- note: where 'Failure' = 'E'
5 | 
[exit 1]

SDK interface 에서 AsyncThrowingStream.Continuation 의 Hashable 선언에는 where 절이 없어서 어떤 Failure 에도 붙는다. 그런데 stream 을 만드는 공개 경로 세 개, init(_:bufferingPolicy:_:) 와 init(unfolding:) 와 makeStream(of:throwing:bufferingPolicy:) 가 모두 where Failure == any Error 제약을 달고 있다. 위 오류의 note 끝에 나온 where Failure == any Error 가 그것이다. 구체 에러 타입으로는 stream 을 만들 수 없으니, 실제로 만들 수 있는 AsyncThrowingStream.Continuation 은 any Error 판이다.


구독자가 들고 나는 Observer

제안서의 Observer 를 6.4 에서 실제로 돌려 봤다. 구독자 A, B 가 sender.values 로 각자 stream 을 받는다. B 는 값이 2 일 때 for await 에서 break 로 나가고, A 는 마지막에 task 를 cancel() 한다. 제안서 코드에서 values 의 반환 타입을 AsyncStream<Int> 로 적고 Sender 를 private class 에서 final class 로 바꾼 다음, onTermination 에서 지운 결과(제거 여부와 남은 개수)를 출력한다.

Observer.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
import Foundation

@MainActor final class Sender {
  var value: Int = 0 {
    didSet { for c in continuations { c.yield(value) } }
  }
  var values: AsyncStream<Int> {
    AsyncStream<Int>(bufferingPolicy: .bufferingNewest(1)) { continuation in
      continuation.yield(value)
      self.continuations.insert(continuation)
      continuation.onTermination = { reason in
        DispatchQueue.main.async {
          let removed = self.continuations.remove(continuation) != nil
          print("onTermination \(reason) removed=\(removed) remaining=\(self.continuations.count)")
        }
      }
    }
  }
  var subscriberCount: Int { continuations.count }
  private var continuations: Set<AsyncStream<Int>.Continuation> = []
}

@main struct M {
  @MainActor static func main() async {
    let sender = Sender()
    let a = Task { for await v in sender.values { print("A got \(v)") } ; print("A done") }
    let b = Task { for await v in sender.values { print("B got \(v)"); if v == 2 { break } } ; print("B done") }
    try? await Task.sleep(for: .milliseconds(30))
    print("subscribers:", sender.subscriberCount)
    sender.value = 1
    try? await Task.sleep(for: .milliseconds(30))
    sender.value = 2
    try? await Task.sleep(for: .milliseconds(30))
    print("subscribers after B break:", sender.subscriberCount)
    a.cancel()
    try? await Task.sleep(for: .milliseconds(30))
    print("subscribers after A cancel:", sender.subscriberCount)
    _ = b
  }
}
1
bash diag.sh Observer.swift
1
[exit 0]
1
2
xcrun swiftc -parse-as-library -swift-version 6 Observer.swift -o obs
./obs
1
2
3
4
5
6
7
8
9
10
11
12
13
A got 0
B got 0
subscribers: 2
B got 1
A got 1
B got 2
B done
A got 2
onTermination cancelled removed=true remaining=1
subscribers after B break: 1
onTermination cancelled removed=true remaining=0
A done
subscribers after A cancel: 0

Task 와 sleep 과 cancel 로 구독자 만들고 끝내기

Task { ... } 는 새 비동기 작업을 시작한다. @MainActor 인 main 안에서 만들어서 구독자 두 개가 main actor 에서 돈다. Task.sleep(for:) 는 주어진 시간만큼 현재 task 를 재우는 함수이고, 구독자가 stream 을 받아 Set 에 들어가고 값이 전해질 시간을 주려고 30ms 씩 썼다. cancel() 는 task 에 취소 요청을 보낸다. for await 는 취소를 보면 순회를 끝낸다.

줄마다 읽기

  • subscribers: 2: sender.values 를 두 번 불러서 build 클로저가 두 번 불렸고, 각 continuation 이 Set 에서 서로 다른 원소다
  • B got 2 와 B done: B 가 break 로 나갔다
  • onTermination cancelled removed=true remaining=1: B 의 stream 이 끝나며 onTermination 이 불렸고 reason 이 cancelled 다. for await 를 break 로 나가면 finished 가 아니라 cancelled 로 알려진다. 읽는 쪽이 읽기를 그만둔 것이기 때문이다. removed=true 는 클로저가 캡처한 continuation(복사본) 으로 remove 했더니 Set 에서 실제로 하나가 빠졌다는 뜻이고, 남은 것은 A 의 continuation 하나다. 이 줄이 Hashable 의 효과다
  • subscribers after B break: 1
  • 두 번째 onTermination cancelled removed=true remaining=0: A 를 cancel() 하자 같은 일이 일어나고 남은 것이 0 이다
  • 구독자 수가 2, 1, 0 으로 줄었다. 지워지지 않은 continuation 은 없다

실행마다 달라지는 줄 순서

같은 실행 파일을 100번 돌렸다. 두 번째로 돈 출력은 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
A got 0
B got 0
subscribers: 2
A got 1
B got 1
A got 2
B got 2
B done
onTermination cancelled removed=true remaining=1
subscribers after B break: 1
onTermination cancelled removed=true remaining=0
A done
subscribers after A cancel: 0

첫 번째 출력과 줄 순서가 다르다. 100번의 결과를 줄 종류별로 나눠 보면 이렇다.

  • A got 과 B got 줄은 A 와 B 두 task 가 main actor 에서 번갈아 도는 순서에 달려서 실행마다 섞인다. 두 가지가 독립적으로 갈린다. 값 0 을 A 가 먼저 받는지 B 가 먼저 받는지, 그리고 값 1 을 누가 먼저 받는지다. 값 1 을 B 가 먼저 받으면 A 가 받는 마지막 값 A got 2 가 B done 뒤로 밀린다. 2 곱하기 2 로 네 가지이고, 100번 돌려서 네 가지가 모두 나왔다(46, 25, 18, 11번)
  • A 와 B 줄 바깥의 줄(subscribers: 와 onTermination 과 A done)은 100번 모두 같은 순서였다. 100번의 출력에서 A got, B got, B done 줄만 지우면 남는 줄이 모두 같다
  • 한 구독자 안의 순서는 항상 같다. B 는 0, 1, 2 순서로 받고 B done 이 마지막이다. onTermination 줄은 항상 B done 뒤에 왔는데, onTermination 이 DispatchQueue.main.async 로 미뤄서 지우기 때문이다. A done 은 두 번째 onTermination 뒤에 왔다

그러니 이 글의 실행 결과를 읽을 때, A 와 B 의 줄이 어느 쪽이 먼저인지는 의미가 없다. 의미 있는 것은 onTermination 과 subscribers 줄이다. 구독자 수의 변화와 removed=true 는 어느 순서에서도 같다.


순회하지 않고 버려진 stream

제안서는 onTermination 을 캡처해도 안전한 이유를 한 문장으로 말한다. onTermination 은 불린 뒤에 버려지고, stream 이 한 번도 순회되지 않고 버려져도 반드시 불린다는 것이다. 이것이 Observer 에서 중요한 이유는, 구독자가 values 를 받아 놓고 읽지 않으면 continuation 이 Set 에 영원히 남을 수 있기 때문이다. 이 두 경우를 쟀다.

Discarded.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
import Foundation

@MainActor final class Registry {
  var continuations: Set<AsyncStream<Int>.Continuation> = []
  func makeValues() -> AsyncStream<Int> {
    AsyncStream<Int> { continuation in
      self.continuations.insert(continuation)
      continuation.onTermination = { reason in
        DispatchQueue.main.async {
          let removed = self.continuations.remove(continuation) != nil
          print("onTermination \(reason) removed=\(removed) remaining=\(self.continuations.count)")
        }
      }
    }
  }
}

@main struct M {
  @MainActor static func main() async {
    let registry = Registry()
    do {
      let unused = registry.makeValues()
      print("registered:", registry.continuations.count)
      _ = unused
    }
    try? await Task.sleep(for: .milliseconds(30))
    print("after scope:", registry.continuations.count)

    let finished = registry.makeValues()
    registry.continuations.first!.finish()
    var it = finished.makeAsyncIterator()
    print("next:", await it.next() as Any)
    try? await Task.sleep(for: .milliseconds(30))
    print("after finish:", registry.continuations.count)
  }
}
1
bash diag.sh Discarded.swift
1
[exit 0]
1
2
xcrun swiftc -parse-as-library -swift-version 6 Discarded.swift -o dis
./dis
1
2
3
4
5
6
registered: 1
onTermination cancelled removed=true remaining=0
after scope: 0
onTermination finished removed=true remaining=0
next: nil
after finish: 0

do { ... } 블록 안에서 stream 을 만들어 Set 에 한 개를 등록하고(registered: 1) 읽지 않은 채 블록을 나갔다. 30ms 뒤 Set 은 비어 있다(after scope: 0). onTermination cancelled removed=true 가 찍혔다. 순회한 적이 없는 stream 이 버려지는 것도 cancelled 로 알려진다. 두 번째는 finish() 를 부르고 한 번 읽어 nil 을 받는 경우다. reason 이 finished 이고 마찬가지로 지워졌다. 20번을 돌려도 출력이 모두 같았다. 이 흐름이 같은 continuation 을 Set 에서 찾아 지울 수 있는 것은 위의 동등성 덕분이다. 어느 경우에도 onTermination 이 캡처한 continuation 이 원본과 같은 원소로 판정되었다.


Identifiable 이 아니라 Hashable

“id 가 있으면 되지 않았나” 라는 생각이 들 수 있어서 Identifiable 인지도 물었다.

Identifiable.swift

1
2
3
4
5
6
func f() {
  let (_, c) = AsyncStream<Int>.makeStream()
  let _: any Identifiable = c
  print(c.id)
}
@main struct M { static func main() { f() } }
1
bash diag.sh Identifiable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Identifiable.swift:3:29: error: value of type 'AsyncStream<Int>.Continuation' does not conform to specified type 'Identifiable'
1 | func f() {
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   let _: any Identifiable = c
  |                             `- error: value of type 'AsyncStream<Int>.Continuation' does not conform to specified type 'Identifiable'
4 |   print(c.id)
5 | }

Identifiable.swift:4:11: error: value of type 'AsyncStream<Int>.Continuation' has no member 'id'
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   let _: any Identifiable = c
4 |   print(c.id)
  |           `- error: value of type 'AsyncStream<Int>.Continuation' has no member 'id'
5 | }
6 | @main struct M { static func main() { f() } }
[exit 1]

Identifiable 이 아니고 id 라는 멤버도 없다. 제안서와 스레드 어디에도 Identifiable 이 나오지 않는다. 내 읽기로는 Identifiable 을 붙이려면 id 의 타입을 정해서 공개해야 하는데, 이 제안서가 원하는 것은 비교와 hash 뿐이어서 Hashable 하나로 충분하기 때문이다. 이 conformance 가 있으면 Set 의 원소로도, Dictionary 의 키로도 쓸 수 있고, 값을 붙이고 싶으면 Dictionary 를 쓰면 된다.


상자 우회를 같은 Observer 로 돌려 보기

우회와 새 conformance 가 같은 결과를 내는지도 봤다. Box.swift 의 상자 우회를 Observer.swift 와 같은 관찰용 코드로 바꾸고(BoxObserver.swift) 같은 main 으로 20번 돌렸다. A got 과 B got 줄을 빼면 20번 모두 같았고, 그 내용은 Observer.swift 의 같은 줄들과 완전히 같았다. 구독자 수 2, 1, 0 과 onTermination cancelled removed=true remaining=1, remaining=0 도 그대로다. 동작은 같고 코드가 짧아졌다. CounterFixed.swift 도 같은 main 으로 돌려서 구독자 수 2, 1, 0 이 같았다.


스레드에서 오간 이야기

pitch 는 2025-02-15 부터, 리뷰는 2025-03-12 부터 03-25 까지였다. 리뷰 중에는 반대 의견이 한 건도 없었다. 시간순으로 짚는다.

pitch (2025-02-15)

저자 Nickolas_Pohilets 가 pitch 를 열었다(#1, 2025-02-15). 본문은 이 글 앞부분에서 본 제안서 Motivation 과 같다. 여러 AsyncStream 의 continuation 을 모아야 하고 onTermination 에서 해당 continuation 을 지워야 하는 경우, 그리고 상자로 감싸는 우회다.

리뷰 (2025-03-12 부터 03-25)

Jumhyn 이 리뷰를 열었다(#1). mickeyl 은 도움이 되는 추가라고 했다(#2, 2025-03-13). CrystDragon 은 +1 을 달면서 back-deploy 가 안 되는 것이 아쉽다고 썼다(#3, 2025-03-13). 이 아쉬움이 실제로 어떤 모양인지는 아래 마이그레이션 절에서 컴파일로 본다. grynspan 은 간단하고 직관적이니 “Ship it!” 이라고 썼다(#4, 2025-03-21).

리뷰가 끝난 뒤 pitch 스레드의 답글 (2025-03-26 부터 27)

리뷰가 끝난 뒤 pitch 스레드에 답글이 이어졌다. RandomHashTags 는 자기 networking library 를 설계하다가 같은 문제를 만났고 결국 다른 자료구조로 풀었다며 환영했다(#2, 2025-03-26). 다음 날 olbo 가 hash 가 필요 없는 길을 내놓았다. values 가 불린 횟수를 세어 번호를 붙이고 번호와 continuation 을 map 으로 묶자는 것이다. 디버깅에도 도움이 된다고 했다(#3, 2025-03-27). 앞에서 Counter.swift 로 옮겨 돌린 방식이 이것이다. Philippe_Hausler 는 ABI 를 안정적으로 유지하면서 넣을 수 있다면 좋은 추가라고 답했다. 번호를 붙이는 우회가 가능하다는 지적은 맞지만, 지금 구현으로는 hash 를 붙이는 데 드는 비용이 작고 사용자가 얻는 눈에 띄는 이득이 있다는 것이다(#4, 2025-03-27). 같은 날 RandomHashTags 가 olbo 에게 답했다(#5). 직접 추적하고 정리하는 것보다 Hashable 하나가 훨씬 단순하다는 것이다. 우회에는 dictionary 조회와 조작의 복잡도와 성능 비용, heap 객체, Sendable 문제, 새 task 를 만드는 일이 따라붙고, 이 타입이 쓰이는 방식에는 단순한 Hashable 로 충분하다는 의견이었다. 이 중 actor 격리와 새 task 를 만드는 일은 Counter.swift 가 낸 오류와 Task { @MainActor in ... } 로 고친 모양에서 실제로 마주쳤다.

수락 (2025-04-05)

Jumhyn 이 리뷰가 끝났고 Language Steering Group 이 수락했다고 알렸다(#5, 2025-04-05). 공지에서는 피드백이 적었고 전적으로 긍정적이었다고 밝히고, Steering Group 이 Async*Stream.Continuation API 에 편의를 더하는 좋은 추가라는 데 동의했다고 적었다(acceptance #1, 2025-04-05). 동등성의 기준이나 onTermination 과의 상호작용에 대한 질문은 스레드에 나오지 않았다. 앞에서 잰 동등성 규칙은 제안서 Detailed design 이 정한 그대로다.


기대 효과

  • 여러 구독자를 받는 AsyncStream 기반 Observer 에서 continuation 을 Set 으로 모으고 onTermination 에서 그대로 지울 수 있다. 상자 class 와 번호표가 사라진다. 구독자 수가 2, 1, 0 으로 줄어드는 것을 Observer.swift 로 확인했다
  • continuation 을 Dictionary 의 키로 써서 구독자 정보(이름, 필터)를 붙여 둘 수 있다. Equality.swift 의 [t1: "a"][t1b] 가 그 모양이다
  • 끝나거나 취소되거나 버려져서 onTermination 이 불릴 때도 같은 원소로 찾아진다. finish 와 순회 종료 뒤에도 동등성이 유지되기 때문이다
  • 구독자가 늘 때마다 class 인스턴스를 할당하고 번호를 관리하던 비용이 없어진다. 비교와 hash 는 stream 내부 저장소의 정체성으로 한다는 것이 제안서의 설명이다

다른 선택지는 왜 안 됐나

제안서에는 Alternatives considered 절이 없고, 대안은 Motivation 에 있는 우회 이야기와 pitch 스레드에서 나온 것이 전부다.

상자 class 에 넣기

앞에서 본 Box.swift 다. 컴파일러가 막지 않고, 같은 OS 대상에서도 동작한다. 비용이 구독자마다 붙는 heap 할당과 열 줄 남짓의 상용구, 사용처마다 한 겹 벗기는 번거로움이다. 대안이 아니라 Hashable 이 없어서 쓰던 길이다.

번호를 세어 Dictionary 에 넣기

olbo 가 pitch 에서 낸 길이다. hash 가 필요 없다는 것이 장점이고 디버깅에 번호가 도움이 된다는 것도 맞다. 단점은 위에서 잰 대로 Sender 가 count 와 Dictionary 를 따로 관리해야 하고, 지우는 일이 새 Task 가 되어서 actor 격리를 맞춰야 한다는 점이다. onTermination 안의 Task {} 는 actor 를 물려받지 못해서 Task { @MainActor in } 로 격리를 적어야 했다. Philippe_Hausler 는 이런 우회가 가능하다는 점을 인정하면서도 Hashable 쪽의 이득이 크다고 봤다(#4).

Identifiable 로 id 를 노출하기

앞에서 본 대로 Identifiable 은 붙지 않았다. id 의 타입을 정해야 하고, 비교와 hash 라는 필요보다 약속이 커진다는 것이 내 읽기다. 제안서와 스레드는 이 길을 거론하지 않았다.


Swift 6 모드와 마이그레이션

소스 호환성은 순수 추가다. 제안서는 retroactive conformance 가 있을 가능성이 낮다고 쓴다. continuation 의 공개 API 에는 Hashable 이나 Equatable 을 구현할 만한 재료가 없었기 때문이다. 앞에서 Sender.swift 와 Box.swift 를 Swift 5, Swift 5 의 complete 검사, Swift 6 으로 컴파일했을 때 모두 진단이 없었다.

1
2
bash diag.sh -swift-version 5 Sender.swift
bash diag.sh -swift-version 5 -strict-concurrency=complete Sender.swift
1
2
[exit 0]
[exit 0]

ABI 도 추가다. 실제로 막히는 곳은 배포 대상 OS 다. 제안서 Implications on adoption 은 새 버전의 표준 라이브러리가 필요하다고만 쓴다. SDK 선언은 anyAppleOS 26.0 이고, 배포 대상을 macOS 15 로 두고 컴파일하면 이렇게 된다.

1
bash diag.sh -target arm64-apple-macos15 Avail.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
Avail.swift:3:7: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
1 | func f() {
  |      `- note: add '@available' attribute to enclosing global function
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   var s: Set<AsyncStream<Int>.Continuation> = []
  |       |- error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
  |       `- note: add 'if #available' version check
4 |   s.insert(c)
5 |   print(c == c)

Avail.swift:3:47: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
1 | func f() {
  |      `- note: add '@available' attribute to enclosing global function
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   var s: Set<AsyncStream<Int>.Continuation> = []
  |                                               |- error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
  |                                               `- note: add 'if #available' version check
4 |   s.insert(c)
5 |   print(c == c)

Avail.swift:4:5: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
1 | func f() {
  |      `- note: add '@available' attribute to enclosing global function
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   var s: Set<AsyncStream<Int>.Continuation> = []
4 |   s.insert(c)
  |     |- error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
  |     `- note: add 'if #available' version check
5 |   print(c == c)
6 | }

Avail.swift:5:11: error: conformance of 'AsyncStream<Element>.Continuation' to 'Equatable' is only available in macOS 26.0 or newer
1 | func f() {
  |      `- note: add '@available' attribute to enclosing global function
2 |   let (_, c) = AsyncStream<Int>.makeStream()
3 |   var s: Set<AsyncStream<Int>.Continuation> = []
4 |   s.insert(c)
5 |   print(c == c)
  |           |- error: conformance of 'AsyncStream<Element>.Continuation' to 'Equatable' is only available in macOS 26.0 or newer
  |           `- note: add 'if #available' version check
6 | }
7 | @main struct M { static func main() { f() } }
[exit 1]

Hashable 을 쓰는 줄마다 conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer 이고, == 에서는 Equatable 이 같은 문장으로 막힌다. 제안서 예제 Sender.swift 를 같은 대상으로 컴파일하면 진단이 6개 나온다. 아래는 오류 줄만 grep 으로 추린 발췌다. 오류마다 add '@available' attribute to enclosing property 같은 note 가 따라붙는다.

1
bash diag.sh -target arm64-apple-macos15 Sender.swift | grep '^Sender.swift.*error:'
1
2
3
4
5
6
Sender.swift:24:69: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
Sender.swift:6:13: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
Sender.swift:6:13: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
Sender.swift:24:17: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
Sender.swift:15:32: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer
Sender.swift:18:40: error: conformance of 'AsyncStream<Element>.Continuation' to 'Hashable' is only available in macOS 26.0 or newer

여섯 곳은 continuations 를 선언한 줄(24행, 두 번), 순회하는 for 줄(6행, 두 번), insert(15행), remove(18행)이다. 이 대상에서 같은 일을 하려면 갈림길이 셋이다.

  • 배포 대상을 26 으로 올릴 수 있으면 그대로 쓴다. @available(macOS 26.0, iOS 26.0, *) 로 감싸는 것도 같은 방법이다
  • 낮은 대상을 유지하면서 새 OS 에서만 새 방식을 쓰려면 if #available 로 나눈다. 낮은 OS 쪽 분기는 따로 짜야 한다
  • 낮은 OS 에서도 같은 동작이 필요하면 상자 우회를 유지한다

두 번째를 AvailGuard.swift 로 컴파일했다. 컴파일러가 각 오류 아래에 add 'if #available' version check 를 note 로 제안하던 그 모양이다.

AvailGuard.swift

1
2
3
4
5
6
7
8
9
10
11
func f() {
  let (_, c) = AsyncStream<Int>.makeStream()
  if #available(macOS 26.0, *) {
    var s: Set<AsyncStream<Int>.Continuation> = []
    s.insert(c)
    print(s.count, c == c)
  } else {
    print("old OS")
  }
}
@main struct M { static func main() { f() } }
1
bash diag.sh -target arm64-apple-macos15 AvailGuard.swift
1
[exit 0]

세 번째는 앞의 Box.swift 를 같은 대상으로 컴파일해도 진단이 없다. Hashable 이 필요한 것은 상자 class 이고 continuation 이 아니기 때문이다.

1
bash diag.sh -target arm64-apple-macos15 Box.swift
1
[exit 0]

CrystDragon 이 리뷰에서 아쉬워한 back-deploy 가 되지 않는 점이 이 갈림길이다. SDK interface 에서 makeStream 은 본문이 interface 에 들어 있고 @backDeployed(before: macOS 14.0, ...) 가 붙어서 낮은 OS 에서도 쓸 수 있다. 반면 Hashable 의 == 와 hash(into:) 와 hashValue 는 본문 없는 선언이라서 OS 26 의 libswift_Concurrency 심볼을 부른다. 이전 OS 의 표준 라이브러리에는 그 심볼이 없다.


정리

  • AsyncStream.Continuation 과 AsyncThrowingStream.Continuation 이 Hashable 이다. SDK 선언은 anyAppleOS 26.0 이고 where 절이 없다
  • 같은 stream 의 continuation 은 복사본과 == 이고 hash 도 같다. onTermination 설정, yield, finish, 순회 종료를 거쳐도 같다. 다른 stream 의 continuation 은 같지 않다. Set([c1, copy, c2]).count 가 2 다
  • onTermination 이 캡처한 복사본으로 Set 에서 지울 수 있다. break 로 나가든 취소하든 순회하지 않고 버려지든 finish 하든 removed=true 였다. 구독자 수는 2, 1, 0 이다
  • Observer 실행에서 A 와 B 줄의 순서는 실행마다 섞인다. onTermination 과 subscribers 줄은 100번 모두 같았다
  • AsyncThrowingStream.Continuation 의 Hashable 선언에는 where 절이 없지만, stream 을 만드는 공개 경로가 모두 Failure == any Error 라서 실제로 만들 수 있는 것은 any Error 판이다
  • Identifiable 은 아니고 ObjectIdentifier 도 continuation 에는 쓸 수 없다. 6.2 이전의 우회는 상자 class 와 번호표였고, 번호표는 onTermination 안의 Task {} 가 actor 를 물려받지 못해 Task { @MainActor in } 로 격리를 적어야 한다
  • macOS 15 대상으로 컴파일하면 Hashable 과 Equatable 모두 only available in macOS 26.0 or newer 로 막힌다. 낮은 OS 를 지원하려면 상자 우회를 유지한다

관련 글


참고자료

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.