포스트

[SE-0518] ~Sendable for explicitly marking non-Sendable types

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


제안서 정보


한 줄 요약

struct Foo: ~Sendable 처럼 상속 절에 ~Sendable 을 적으면 그 타입은 Sendable 이 아니라고 명시한 것이 된다. ~Copyable 이나 ~Escapable 과 같은 “억제” 표기를 Sendable 에 가져온 것이다. 필요한 이유는 둘이다. public 타입에 Sendable 표시가 없을 때 “아직 안 붙인 것인지 일부러 뺀 것인지” 가려낼 길이 없었고, 기존 방법인 @available(*, unavailable) extension X: Sendable 은 하위 클래스까지 영원히 non-Sendable 으로 묶어 버렸다. ~Sendable 은 그 타입 자신만 non-Sendable 으로 두고 하위 클래스가 @unchecked Sendable 을 다는 길을 열어 둔다. 이 글은 어디에 붙일 수 있고 어디에는 붙일 수 없는지, Sendable 을 요구하는 자리에서 어떤 진단이 나오는지, 하위 클래스와 조건부 Sendable 이 어떻게 움직이는지, 감사 진단 ExplicitSendable 이 무엇을 잡는지를 Swift 6.4 컴파일러로 하나씩 재 본다.


어떤 문제였나

Sendable 은 “여러 스레드와 actor 사이를 오가도 안전한 타입” 이라는 표시다. 이 표시가 붙은 타입만 actor 의 경계를 넘어갈 수 있어서, Swift 6 의 data-race 검사는 대부분 Sendable 이 있느냐 없느냐를 묻는 검사다. 그런데 “없다” 에는 두 가지 뜻이 섞여 있다. 아직 붙이지 않았다는 뜻일 수도 있고, 안전하지 않아서 일부러 뺐다는 뜻일 수도 있다. SE-0518 은 이 둘을 코드로 구분하게 해 주는 제안이다.

이 글은 문제를 네 겹으로 본다. 먼저 컴파일러가 Sendable 을 알아서 붙여 주는 추론이 무엇인지 보고, 그 추론이 닿지 않는 public 타입에서 의도가 사라지는 문제를 보고, 지금까지 non-Sendable 을 못 박던 방법 unavailable extension 이 어디서 막히는지를 측정하고, 마지막으로 현장에서 이 문제가 어떻게 불편했는지를 포럼 글로 본다. 시리즈의 앞 글들은 필요한 만큼만 짚는다.

  • SE-0434 글: @MainActor 가 붙은 클래스가 Sendable 이 되는 규칙. 그 글의 Alternatives Considered 는 자식 클래스에 ~Sendable 같은 opt-out 표기를 요구하는 안을 검토하고 택하지 않았다. 이 글의 제안이 그 표기를 선언 자리로 들여온 것이고, 뒤의 “억제와 conformance 의 충돌” 절에서 @MainActor 클래스와 만난다
  • SE-0418 글: 메서드와 key path 의 Sendable 추론. 이 글의 “추론” 과 같은 주제의 다른 자리다. 그 글의 pitch 에서 ktoso 가 errno() 같은 함수를 non-Sendable 으로 적는 @~Sendable 표기가 필요하냐고 물었고, 제안서에는 들어가지 않았다. non-Sendable 을 코드로 적는 자리가 없다는 같은 아쉬움이 함수 쪽에서 먼저 나온 셈이다
  • SE-0414 글: region based isolation. ~Sendable 타입을 경계 너머로 보낼 때 나오는 오류가 이 검사에서 나온다

Sendable 추론이란?

컴파일러는 어떤 타입에는 Sendable 을 직접 적지 않아도 “이 타입은 Sendable 이다” 라고 판단해 준다. 이것이 추론(inference)이다. 규칙은 간단하다. 같은 모듈 안에서만 쓰이는(internal) struct 와 enum 은 저장 속성이나 case 의 연관값이 모두 Sendable 이면 암묵적으로 Sendable 이 된다. 반대로 public 타입과 class 는 추론하지 않는다. public 타입은 나중에 저장 속성을 바꿀 수 있어서 Sendable 이라는 약속을 컴파일러가 대신 해 주면 API 계약이 의도치 않게 생기기 때문이고, class 는 가변 상태를 가질 수 있어서 final 에 불변 속성만 있는 경우를 사람이 직접 보증하게 한다. 예외가 하나 있다. @frozen public struct 는 public 이어도 추론된다. @frozen 은 저장 속성의 배치를 ABI 로 못 박는 표시라서 속성을 나중에 바꿀 수 없고, 그러니 Sendable 을 컴파일러가 대신 판단해도 뒤집힐 약속이 생기지 않는다. 이 예외는 아래에서 재고, “인터페이스 파일” 절과 “소스 호환” 절에서 다시 만난다. actor 는 처음부터 늘 Sendable 이다.

아래 코드로 직접 본다. 세 타입이 모두 Sendable 을 요구하는 함수 processData 에 들어간다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func processData<T: Sendable>(_ data: T) { }

struct Inner {
    let value: Int
}

public struct Outer {
    let value: Int
}

final class Box {
    var n = 0
}

struct Holder {
    let box: Box
}

func run() {
    processData(Inner(value: 1))
    processData(Outer(value: 1))
    processData(Holder(box: Box()))
}
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
Infer.swift:21:5: error: type 'Outer' does not conform to the 'Sendable' protocol
 5 | }
 6 | 
 7 | public struct Outer {
   |               `- note: consider making struct 'Outer' conform to the 'Sendable' protocol
 8 |     let value: Int
 9 | }
   :
19 | func run() {
20 |     processData(Inner(value: 1))
21 |     processData(Outer(value: 1))
   |     `- error: type 'Outer' does not conform to the 'Sendable' protocol
22 |     processData(Holder(box: Box()))
23 | }

Infer.swift:22:5: error: type 'Holder' does not conform to the 'Sendable' protocol
13 | }
14 | 
15 | struct Holder {
   |        `- note: consider making struct 'Holder' conform to the 'Sendable' protocol
16 |     let box: Box
17 | }
   :
20 |     processData(Inner(value: 1))
21 |     processData(Outer(value: 1))
22 |     processData(Holder(box: Box()))
   |     `- error: type 'Holder' does not conform to the 'Sendable' protocol
23 | }
24 |

Inner 는 internal 이고 저장 속성이 Int 뿐이라 추론되어 통과했다. Outer 는 저장 속성이 똑같아도 public 이라서 추론이 일어나지 않고 오류가 난다. Holder 는 internal 이지만 non-Sendable 인 Box 를 들고 있어서 추론이 안 된다. 두 오류의 note 가 모두 “Sendable 로 만들어 보라” 고 권하는 것이 눈에 띈다. 컴파일러는 이 타입이 Sendable 이 아닌 이유를 알 수 없고, 사람이 Sendable 을 달면 된다는 가능성만 연다.

Sendable 요구로 타입 걸러내기

Sendable 은 요구사항이 없는 marker protocol 이다. func processData<T: Sendable> 처럼 제네릭 매개변수에 Sendable 을 걸면, 그 자리에는 Sendable 인 타입만 들어올 수 있다. 이 코드에서는 타입이 Sendable 인지 아닌지를 컴파일러가 어떻게 판단하는지를 보려고 쓴 장치다. Sendable 에는 메서드가 없으므로 conformance 를 적는 것은 “이 타입은 안전하다” 는 선언일 뿐이고, 그 선언이 정말 맞는지는 컴파일러가 저장 속성으로 검사한다. 검사를 건너뛰고 사람이 책임지겠다고 하려면 @unchecked Sendable 을 쓴다.

public 타입은 추론하지 않는다는 규칙의 @frozen 예외도 같은 방식으로 잰다. 같은 모양의 public struct 두 개에 @frozen 만 다르게 달아 processData 에 넣는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func processData<T: Sendable>(_ data: T) { }

@frozen public struct Frozen {
    public let id: Int
}

public struct NonFrozen {
    public let id: Int
}

func run() {
    processData(Frozen(id: 1))
    processData(NonFrozen(id: 1))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Frozen.swift:13:5: error: type 'NonFrozen' does not conform to the 'Sendable' protocol
 5 | }
 6 |
 7 | public struct NonFrozen {
   |               `- note: consider making struct 'NonFrozen' conform to the 'Sendable' protocol
 8 |     public let id: Int
 9 | }
   :
11 | func run() {
12 |     processData(Frozen(id: 1))
13 |     processData(NonFrozen(id: 1))
   |     `- error: type 'NonFrozen' does not conform to the 'Sendable' protocol
14 | }
15 |

@frozen 인 Frozen 은 통과하고 @frozen 이 아닌 NonFrozen 만 오류다. 라이브러리 진화 모드를 켜고 모듈을 만들어도 @frozen 타입의 추론은 같다.


표시가 없는 public 타입의 의도

앞 측정의 Outer 를 라이브러리가 배포한 public 타입이라고 해 보자. 클라이언트가 이 타입을 Sendable 자리에 쓰려다 오류를 만난다. 이 타입에 Sendable 이 없는 이유는 세 가지일 수 있다.

  • 라이브러리 작성자가 Sendable 을 붙이는 것을 잊었다
  • 안에 동기화되지 않은 가변 상태가 있어서 일부러 붙이지 않았다
  • 지금은 불변이지만 나중에 상태를 추가할 여지를 남기려고 붙이지 않았다

세 경우가 겉으로는 똑같이 보인다. 제안서 Motivation 은 이것을 이렇게 정리한다. 의도를 가려내려면 타입의 저장 구조와 공유 상태를 보호하는 동기화 방식을 알아야 하는데, 그것은 라이브러리 밖에서는 볼 수 없는 구현 세부사항이라는 것이다. 라이브러리 작성자가 자기 API 전체를 점검하는 Sendable 감사(audit)를 하더라도, 점검을 끝낸 결과를 소스에 남길 방법이 마땅치 않았다. Sendable 이라고 적으면 Sendable 이고, “점검했더니 Sendable 이 아니었다” 를 적을 자리가 없었다.


unavailable extension 이란?

지금까지 있던 유일한 방법이 unavailable extension 이다. 타입에 Sendable conformance 를 붙이되 “이 conformance 는 쓸 수 없다” 고 표시하는 것이다. 문 앞에 “사용 금지” 푯말을 붙이는 것과 같다. 문(conformance)은 있지만 열 수 없다. 컴파일러는 이 푯말을 보고 이 타입을 Sendable 로 추론하지도 않고, Sendable 자리에 들어오는 것도 막는다.

제안서 Motivation 의 예를 그대로 재 본다. 부모 Base 에 푯말을 붙이고, 하위 클래스 ThreadSafe 가 안에서 스스로 스레드 안전을 보장한다고 @unchecked Sendable 을 단다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func takesSendable<T: Sendable>(_: T) {}

class Base {
}

@available(*, unavailable)
extension Base: Sendable {
}

final class ThreadSafe: Base, @unchecked Sendable {
}

func run() {
    takesSendable(ThreadSafe())
}
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
Old.swift:10:42: warning: 'ThreadSafe' inherits an unavailable 'Sendable' conformance; conforming here risks data races [#UnavailableSendableConformance]
 8 | }
 9 | 
10 | final class ThreadSafe: Base, @unchecked Sendable {
   |             |                            `- warning: 'ThreadSafe' inherits an unavailable 'Sendable' conformance; conforming here risks data races [#UnavailableSendableConformance]
   |             `- note: 'ThreadSafe' inherits unavailable conformance to protocol 'Sendable' from superclass here
11 | }
12 | 

Old.swift:14:5: error: conformance of 'Base' to 'Sendable' is unavailable
 5 | 
 6 | @available(*, unavailable)
 7 | extension Base: Sendable {
   | `- note: conformance of 'Base' to 'Sendable' has been explicitly marked unavailable here
 8 | }
 9 | 
   :
12 | 
13 | func run() {
14 |     takesSendable(ThreadSafe())
   |     `- error: conformance of 'Base' to 'Sendable' is unavailable
15 | }
16 | 

[#UnavailableSendableConformance]: <https://docs.swift.org/compiler/documentation/diagnostics/unavailable-sendable-conformance>

하위 클래스가 @unchecked Sendable 이라고 선언했는데도 두 가지가 일어난다. 선언 자리에서는 “물려받은 unavailable conformance 가 있는데 여기서 conform 하면 data race 위험이 있다” 는 경고가 나고, 쓰는 자리에서는 ThreadSafe 가 아니라 부모 Base 의 conformance 가 unavailable 이라는 오류가 난다. 이 상태가 제안서가 말하는 문제다. conformance 는 다른 모든 conformance 처럼 하위 클래스로 상속되고, unavailable 은 “이 타입은 하위 클래스까지 포함해서 영원히 Sendable 이 아니다” 라는 뜻이 된다. 부모는 Sendable 이 아니지만 하위 클래스 중 일부는 Sendable 일 수 있다는 “세 번째 상태” 는 이 문법으로는 쓸 수 없었다.


현장에서 나온 불편

포럼 글이 이 문제를 구체적으로 보여 준다. jmschonfeld 는 pitch #4 에서 Foundation 에 부모는 구체적으로 non-Sendable 이라고 말할 수 없는데 Sendable 하위 클래스와 non-Sendable 하위 클래스를 둘 다 가진 클래스가 여럿이라, 완전성을 위해 부모에 표시를 하고 싶어도 지금까지 못 했다고 했다. 그 글에는 swift-corelibs-foundation 에서 @_nonSendable 을 검색한 결과 링크가 달려 있다. 부모를 표시할 수 없어서 남겨 둔 흔적이라는 이야기다. 리뷰 #3 에서는 같은 내용을 코드 주석으로 적어 왔다고 설명하고, Foundation 에서 -require-explicit-sendable 로 Sendable 감사 누락을 막고 싶었는데 ~Sendable 이 없어 쓰지 못했다고 덧붙였다.

dnadoba 는 pitch #13 에서 Sendable 을 붙인 다음 unavailable 로 막는 이유를 설명하느라 오래 대화한 적이 많다고 했다. Swift 5.5 가 나왔을 때 이 표기를 위한 Xcode 스니펫을 직접 만들고 구버전 Swift 를 위한 가드까지 적었다는 이야기다. 짧고 편하게 쓸 수 있는 표기가 있으면 좋겠다는 쪽이다. ktoso 도 리뷰 #9 에서 서버 생태계의 몇몇 타입을 지금까지 unavailable 로 버텨 왔고 이쪽이 낫다고 했다.


무엇이 바뀌나

변경은 한 문장이다. struct, enum, class 의 선언 줄에 ~Sendable 을 적으면 Sendable 추론을 억제하고 그 타입은 Sendable 이 아니라고 못 박는다. 아래는 그 규칙의 경계를 한 절씩 재 본다. 모든 측정은 Swift 6.4(swiftlang-6.4.0.34.1)의 -emit-sil -parse-as-library -wmo 결과이고, -swift-version 6 이다.


억제 표기란?

~ 는 이미 Swift 에 있는 표기다. ~Copyable, ~Escapable, ~BitwiseCopyable 이 그렇다. 이 프로토콜들은 컴파일러가 알아서 붙여 주는 것들이다. 모든 타입은 기본으로 Copyable 이고, 조건이 맞는 타입은 BitwiseCopyable 이 추론된다. ~ 는 “그 기본 추론을 끄겠다” 는 뜻이다. 풀어 쓰면 “컴파일러야, 이 conformance 는 알아서 붙이지 마라” 이고, 구체적인 타입에서는 결과적으로 “이 프로토콜을 따르지 않는다” 와 같다.

pitch 스레드에서 이 뜻을 두고 작은 논쟁이 있었다. 8675309 는 #14 와 #20 에서 ~ 가 “추론하지 마라” 일 뿐이고 “Sendable 아님” 이 아니라면, 억제한 뒤 extension 으로 Sendable 을 다시 붙이는 것은 왜 막느냐고 물었다. xedin 은 #19 와 #21 에서 억제하면서 동시에 conform 하는 것은 모순이라고 답했다. allevato 는 #22 에서 ~BitwiseCopyable 도 똑같이 막힌다는 코드로 보여 주고 이렇게 정리했다. 구체 타입에서 ~P 는 “P 를 따르지 않는다” 이고, 제네릭 매개변수의 <T: ~P> 는 “P 를 요구하지 않는다(그래도 따를 수는 있다)” 이다. 구체 타입에서는 “추론을 끈다” 와 “따르지 않는다” 가 같은 말이라는 설명이다.

같은 표기라도 어디에 쓸 수 있는지는 프로토콜마다 다르다. ~Sendable 이 막힌 자리(extension, protocol, 제네릭 매개변수, actor)에 ~Copyable 과 ~BitwiseCopyable 을 하나씩 놓고 재 본다.

1
2
3
4
5
6
7
8
9
10
11
protocol P1: ~Copyable {}
struct Box1<T: ~Copyable>: ~Copyable { var t: T }
func f1<T: ~Copyable>(_: borrowing T) {}
struct S1 {}
extension S1: ~Copyable {}
protocol P2: ~BitwiseCopyable {}
struct Box2<T: ~BitwiseCopyable> {}
struct S2 {}
extension S2: ~BitwiseCopyable {}
public struct Pub: ~Copyable {}
actor Ac: ~Copyable {}
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
Cp.swift:5:1: error: cannot suppress 'Copyable' in extension
 3 | func f1<T: ~Copyable>(_: borrowing T) {}
 4 | struct S1 {}
 5 | extension S1: ~Copyable {}
   | `- error: cannot suppress 'Copyable' in extension
 6 | protocol P2: ~BitwiseCopyable {}
 7 | struct Box2<T: ~BitwiseCopyable> {}

Cp.swift:6:14: warning: conformance to 'BitwiseCopyable' can only be suppressed on structs, classes, and enums; this will be an error in a future Swift language mode
 4 | struct S1 {}
 5 | extension S1: ~Copyable {}
 6 | protocol P2: ~BitwiseCopyable {}
   |              `- warning: conformance to 'BitwiseCopyable' can only be suppressed on structs, classes, and enums; this will be an error in a future Swift language mode
 7 | struct Box2<T: ~BitwiseCopyable> {}
 8 | struct S2 {}

Cp.swift:7:16: warning: conformance to 'BitwiseCopyable' can only be suppressed on structs, classes, and enums; this will be an error in a future Swift language mode
 5 | extension S1: ~Copyable {}
 6 | protocol P2: ~BitwiseCopyable {}
 7 | struct Box2<T: ~BitwiseCopyable> {}
   |                `- warning: conformance to 'BitwiseCopyable' can only be suppressed on structs, classes, and enums; this will be an error in a future Swift language mode
 8 | struct S2 {}
 9 | extension S2: ~BitwiseCopyable {}

Cp.swift:9:1: error: conformance to inferrable protocol 'BitwiseCopyable' cannot be suppressed in an extension
 7 | struct Box2<T: ~BitwiseCopyable> {}
 8 | struct S2 {}
 9 | extension S2: ~BitwiseCopyable {}
   | `- error: conformance to inferrable protocol 'BitwiseCopyable' cannot be suppressed in an extension
10 | public struct Pub: ~Copyable {}
11 | actor Ac: ~Copyable {}

Cp.swift:11:7: error: actors cannot be '~Copyable'
 9 | extension S2: ~BitwiseCopyable {}
10 | public struct Pub: ~Copyable {}
11 | actor Ac: ~Copyable {}
   |       `- error: actors cannot be '~Copyable'
12 |

세 표기를 같은 자리에 놓고 모으면 이렇다.

자리~Copyable~BitwiseCopyable~Sendable
extensionerrorerrorerror
protocol 의 상속 절허용warningerror
제네릭 매개변수허용warningerror
actorerror해당 없음error

~Copyable 이 protocol 과 제네릭 매개변수에서 허용되는 이유는 Copyable 이 모든 타입, 제네릭 매개변수, protocol 에 암묵적으로 걸린 요구이기 때문이다. <T: ~Copyable> 은 그 암묵적 요구를 끈다는 뜻이라 의미가 있다. Slava_Pestov 가 pitch #23 에서 이 점을 짚었다. Sendable 은 제네릭 매개변수에 암묵적 요구가 없고 추론도 non-public 인 nominal type 에만 일어난다. 그래서 <T: ~Sendable> 에는 끌 것이 없고 6.4 는 이것을 오류로 막는다. 더 근본적인 차이도 있다. ~Copyable 은 타입의 의미를 바꾼다. 복사할 수 없는 타입이 되어서 쓰는 방식이 달라진다. ~Sendable 은 conformance 하나를 빼는 것이 전부이고 타입의 값 의미는 그대로다.

억제해 놓고 extension 으로 다시 붙이는 것을 허용할지는 Slava_Pestov 가 같은 글에서 “임의의 선택(arbitrary choice)” 이라고 했다. 금지하려면 컴파일러에 로직이 더 필요하지만 스타일로는 금지하는 쪽이 낫다는 판단이다. ~Sendable 은 금지하는 쪽을 택했고 뒤의 “억제와 conformance 의 충돌” 절의 오류가 그 결과다.


붙일 수 있는 자리와 없는 자리

~Sendable 은 struct, enum, class 의 선언 자체에만 쓸 수 있다. 네 군데를 한 파일에 놓고 재 본다.

1
2
3
4
5
6
struct Test {}
extension Test: ~Sendable {}

protocol P: ~Sendable {}
struct Box<T: ~Sendable> {}
func test<T: ~Sendable>(_: T) {}
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
Errors.swift:2:1: error: conformance to inferrable protocol 'Sendable' cannot be suppressed in an extension
1 | struct Test {}
2 | extension Test: ~Sendable {}
  | `- error: conformance to inferrable protocol 'Sendable' cannot be suppressed in an extension
3 | 
4 | protocol P: ~Sendable {}

Errors.swift:4:13: error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
2 | extension Test: ~Sendable {}
3 | 
4 | protocol P: ~Sendable {}
  |             `- error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
5 | struct Box<T: ~Sendable> {}
6 | func test<T: ~Sendable>(_: T) {}

Errors.swift:5:15: error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
3 | 
4 | protocol P: ~Sendable {}
5 | struct Box<T: ~Sendable> {}
  |               `- error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
6 | func test<T: ~Sendable>(_: T) {}
7 | 

Errors.swift:6:14: error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
4 | protocol P: ~Sendable {}
5 | struct Box<T: ~Sendable> {}
6 | func test<T: ~Sendable>(_: T) {}
  |              `- error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
7 | 

네 줄이 모두 오류다. 이유는 각각 다르다.

  • extension: 타입 선언 밖에서 억제하면 이미 있는 코드의 의미가 바뀔 수 있다. 어떤 파일의 extension 한 줄이 다른 곳에서 Sendable 로 쓰이던 타입을 갑자기 Sendable 이 아니게 만들 수 있기 때문이다. 제안서가 든 이유이고, jmschonfeld 가 pitch #4 에서 물었을 때 xedin 이 #5 에서 ~BitwiseCopyable 처럼 상속 절에만 쓸 수 있다고 답했다
  • protocol: 프로토콜에는 억제할 추론이 없다. duan 이 pitch #9 에서 물었고 xedin 이 #10 에서 class, struct, enum 에만 된다고 답했다
  • 제네릭 매개변수: 제네릭 매개변수는 Sendable 요구를 따로 적지 않으면 이미 Sendable 이 아닌 타입도 받는다. 억제할 것이 없다는 설명이다. Copyable 은 제네릭 매개변수에 암묵적 요구가 있어서 <T: ~Copyable> 이 의미가 있지만 Sendable 은 그런 요구가 없다. 앞의 Cp.swift 가 이 차이를 보여 준다

세 번째가 가장 많이 거론되었다. xwu 는 pitch #2 에서 <T: ~Sendable> 과 <T> 는 같은 뜻인데 컴파일러가 꼭 거부해야 하느냐고 물었고, xedin 은 #3 에서 ~BitwiseCopyable 과 맞추려는 것이지만 경고로 바꿀 수도 있다고 답했다. 리뷰에서 grynspan 이 #10 에서 no-op 이라도 일관성을 위해 허용하는 편이 낫다고 했다. 6.4 컴파일러에서는 5번 줄의 struct Box<T: ~Sendable> 와 6번 줄의 func test<T: ~Sendable> 모두 오류다. 경고가 아니다. 같은 자리에서 ~BitwiseCopyable 은 경고다.

ksluder 는 리뷰 #2 에서 플랫폼마다 Sendable 감사 시점이 다를 때 @available(toasterOS 4.0, *) extension ParentClass: ~Sendable 처럼 쓰고 싶다고 했다. 이런 extension 이 바로 위의 2번 줄에서 막힌 형태다. xedin 은 #5 에서 원하는 플랫폼에서만 조건부 Sendable 으로 만들면 나머지는 non-Sendable 이 된다고 답했다. 조건부 Sendable 은 뒤의 절에서 본다.

actor 는 별도다. actor 는 늘 Sendable 이라서 억제할 수 없다. 뒤의 “억제와 conformance 의 충돌” 절의 첫 측정이다.


Sendable 요구와 진단

~Sendable 타입은 unavailable extension 과 똑같이 Sendable 요구를 만족시키지 못한다. 앞의 Inner, Outer 와 같은 모양의 타입을 Plain 과 NotSendable 으로 나란히 둔다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func processData<T: Sendable>(_ data: T) { }

struct NotSendable: ~Sendable {
    let value: Int
}

struct Plain {
    let value: Int
}

func run() {
    processData(Plain(value: 1))
    processData(NotSendable(value: 42))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Basic.swift:13:5: error: type 'NotSendable' does not conform to the 'Sendable' protocol
 1 | func processData<T: Sendable>(_ data: T) { }
 2 | 
 3 | struct NotSendable: ~Sendable {
   |        `- note: struct 'NotSendable' explicitly suppresses conformance to 'Sendable' protocol
 4 |     let value: Int
 5 | }
   :
11 | func run() {
12 |     processData(Plain(value: 1))
13 |     processData(NotSendable(value: 42))
   |     `- error: type 'NotSendable' does not conform to the 'Sendable' protocol
14 | }
15 | 

두 타입은 저장 속성이 똑같고 ~Sendable 표시만 다르다. 표시 없는 Plain 은 internal struct 의 Int 하나라 추론되어 통과하고, NotSendable 은 오류다. 오류 메시지는 앞의 Outer 와 같지만 note 가 다르다. Outer 에는 “conform 해 보라” 는 제안이 붙었는데, 여기에는 “이 struct 가 Sendable conformance 를 명시적으로 억제했다” 는 note 가 붙어서 의도적인 non-Sendable 임을 알려 준다. 사용자는 이 note 로 “붙이는 것을 잊은 것이 아니구나” 를 한눈에 안다.

Sendable 을 요구하는 자리의 오류 수준은 언어 모드가 정한다. 같은 파일을 세 모드로 재 본다. 모드 옵션 -strict-concurrency=complete 는 SE-0337 글에서 다룬 점진적 마이그레이션의 옵션이다. 이 글의 다른 진단도 같은 방식으로 재서 한 표에 모은다.

진단Swift 5Swift 5 + -strict-concurrency=completeSwift 6
~Sendable 타입을 Sendable 자리에 넣기 (Basic.swift)없음warning (; this is an error in the Swift 6 language mode)error
억제를 쓸 수 없는 자리 (Errors.swift 의 extension, protocol, 제네릭 매개변수)errorerrorerror
억제하면서 conform (Both.swift, Direct.swift)errorerrorerror
~Sendable 부모의 하위 클래스에 검사받는 Sendable (Mixed.swift 4:13)warningwarningerror

declaration 자리의 오류(어디에 붙일 수 있는가, 억제와 conformance 의 모순)는 언어 모드와 상관없이 error 다. 모드를 따르는 것은 Sendable 을 요구하는 사용 자리와 NonSendableSuperclass 이고, 이 중 사용 자리는 Swift 5 모드에서 조용하다. 명시적으로 ~Sendable 을 달아도 Basic.swift, Inference2.swift, Conditional.swift 는 Swift 5 에서 진단이 없었다. 경계에서 값을 넘기는 코드에서는 이 차이가 더 크다. 아래 코드는 이 글에서 가장 실용적인 측정이다. internal Point 는 Sendable 로 추론되고 Token 은 같은 모양에 ~Sendable 을 달았다. 둘을 actor 의 메서드와 Task.detached 에 각각 넘긴다.

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
struct Point {
    let x: Int
}

struct Token: ~Sendable {
    let x: Int
}

actor Store {
    var lastPoint: Point?
    var lastToken: Token?
    func keep(_ p: Point) { lastPoint = p }
    func keep(_ t: Token) { lastToken = t }
}

func sendPoint(store: Store, p: Point) async {
    await store.keep(p)
}

func sendToken(store: Store, t: Token) async {
    await store.keep(t)
}

func capturePoint(_ p: Point) {
    Task.detached { print(p) }
}

func captureToken(_ t: Token) {
    Task.detached { print(t) }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Inference2.swift:21:17: error: sending 't' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 | 
20 | func sendToken(store: Store, t: Token) async {
21 |     await store.keep(t)
   |                 |- error: sending 't' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                 `- note: sending 't' to actor-isolated instance method 'keep' risks causing data races between actor-isolated code and code in the current isolation context
22 | }
23 | 

Inference2.swift:29:10: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
27 | 
28 | func captureToken(_ t: Token) {
29 |     Task.detached { print(t) }
   |          |                `- note: closure captures 't' which is accessible to code in the current isolation context
   |          `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
30 | }
31 | 

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>

Point 쪽 두 함수는 진단이 없고 Token 쪽 두 함수만 오류다. 오류 이름이 Sendable 이 아니라 RegionIsolation 인 점이 흥미롭다. Sendable 이면 아무 때나 경계를 넘을 수 있고, Sendable 이 아닌 값은 SE-0414 글에서 본 region 분석이 “이 값을 보낸 뒤 보낸 쪽에서 더 쓰지 않는다” 를 증명할 수 있을 때만 SE-0430 글에서 본 sending 으로 넘길 수 있다. captureToken 이나 sendToken 의 매개변수 t 는 호출한 쪽도 계속 쓸 수 있는 값이라 그 증명이 안 되어 오류가 난다. 이 글의 요점은 ~Sendable 이 추론되는 Sendable 의 자리에 region 분석이 대신 서는 문턱을 만든다는 것이다. 같은 Int 하나짜리 struct 인데 추론에 맡기면 경계를 자유롭게 넘고 ~Sendable 을 달면 region 분석의 심사를 받는다.

이 코드를 세 모드로 재면 Swift 5 는 진단이 없고, Swift 5 complete 는 두 곳이 모두 warning(; this is an error in the Swift 6 language mode), Swift 6 은 두 곳이 error 다.

Task.detached로 클로저를 다른 isolation 에 보내기

Task.detached 는 현재 task 의 actor 와 우선순위와 task-local 값을 물려받지 않는 새 task 를 만든다. 마지막 인자 operation 클로저는 SE-0430 글에서 다룬 sending 으로 받는다. 클로저가 캡처하는 값이 이 호출 뒤에 호출한 쪽에서 더는 접근되지 않아야 한다는 뜻이다. Point 는 Sendable 이라 캡처가 문제 되지 않고, Token 은 Sendable 이 아니라서 호출한 함수의 매개변수 t 를 계속 쓸 수 있는 상태로 캡처해 오류가 났다. actor Store 의 keep(_:) 는 actor 의 격리된 상태를 바꾸는 메서드다. 밖에서 부를 때 await 가 필요하고, 인자는 Sendable 이거나 sending 으로 넘겨야 한다.


하위 클래스

~Sendable 의 핵심은 상속이다. 앞에서 unavailable 이 막은 구성을 ~Sendable 로 바꾼다. 제안서 Detailed design 의 A 와 B 다. 이 코드를 AB.swift 로 저장해 재 본다.

1
2
3
4
5
6
7
8
9
10
11
func takesSendable<T: Sendable>(_: T) {}

class A: ~Sendable {
}

final class B: A, @unchecked Sendable {
}

func run() {
    takesSendable(B())
}

이 코드는 진단이 없다([exit 0]). 같은 구성에서 Base 의 unavailable extension 을 class A: ~Sendable 로 바꿨을 뿐인데 경고도 오류도 사라졌다. 그림으로 두 결과를 나란히 놓는다.

부모에 unavailable extension 을 붙이면 하위 클래스의 @unchecked Sendable 이 경고와 함께 무시되어 takesSendable 에서 오류가 나고, 부모에 ~Sendable 을 적으면 하위 클래스의 @unchecked Sendable 이 살아서 takesSendable 이 통과한다

왼쪽에서는 unavailable conformance 가 상속되어 ThreadSafe 가 Base 의 오류를 그대로 물려받는다. 오른쪽에서는 ~Sendable 이 A 자신에게만 적힌 표시라서 B 는 그 표시를 물려받지 않고 자기 conformance 를 가진다. 이 차이를 제안서는 “~Sendable conformance 는 하위 클래스에 영향을 주지 않는다” 로 요약한다.

다만 부모가 non-Sendable 이므로 하위 클래스가 Sendable 이 되는 길은 한 가지뿐이다. @unchecked 를 붙이는 것이다. 이것도 같은 파일에서 재 본다.

1
2
3
4
5
6
7
8
struct Twice: ~Sendable, @unchecked Sendable {}

class A: ~Sendable {}
final class Checked: A, Sendable {}
final class Unchecked: A, @unchecked Sendable {
    var count = 0
}
class Open: A, @unchecked Sendable {}
1
2
3
4
5
6
7
8
9
10
11
Mixed.swift:4:13: error: class 'Checked' cannot conform to the 'Sendable' protocol [#NonSendableSuperclass]
2 | 
3 | class A: ~Sendable {}
4 | final class Checked: A, Sendable {}
  |             |        `- note: inherits from non-Sendable class 'A'
  |             |- error: class 'Checked' cannot conform to the 'Sendable' protocol [#NonSendableSuperclass]
  |             `- note: a 'Sendable' class cannot inherit from a non-Sendable class
5 | final class Unchecked: A, @unchecked Sendable {
6 |     var count = 0

[#NonSendableSuperclass]: <https://docs.swift.org/compiler/documentation/diagnostics/non-sendable-superclass>

검사받는 Sendable 은 오류다. 이유는 Sendable class 가 non-Sendable 부모를 가질 수 없다는 기존 규칙이다. 컴파일러는 부모에서 이어받은 상태가 안전한지 알 수 없다. 그래서 부모가 non-Sendable 인 하위 클래스를 Sendable 로 만들려면 “책임은 내가 진다” 는 @unchecked Sendable 을 쓸 수밖에 없다. 같은 파일의 Unchecked(가변 속성 count 를 가진 final class)와 상속을 열어 둔 Open 은 진단이 없다. @unchecked 는 컴파일러의 검사를 끄는 약속이라서 var 가 있어도, final 이 아니어도 통과한다.

위의 Twice 줄도 눈여겨볼 만하다. 같은 타입에 ~Sendable 과 @unchecked Sendable 을 함께 적었는데 진단이 없다. 이것은 뒤의 “억제와 conformance 의 충돌” 절에서 다시 본다.


억제와 conformance 의 충돌

~Sendable 과 Sendable 을 한 타입에 동시에 적으면 모순이다. 제안서는 이 규칙이 직접 적은 경우뿐 아니라 슈퍼클래스와 프로토콜에서 물려받은 Sendable 에도 적용된다고 적고 네 가지 예를 든다. 그 예들을 한 파일에 모아 재 본다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
actor A: ~Sendable {
}

struct Container<T>: ~Sendable {
    let value: T
}

extension Container: Sendable {}

protocol IsolatedProtocol: Sendable {
}

struct Test: IsolatedProtocol, ~Sendable {
}

@MainActor
class IsolatedBase {
}

class Refined: IsolatedBase, ~Sendable {
}
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
Both.swift:1:10: error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
 1 | actor A: ~Sendable {
   |          `- error: conformance to 'Sendable' can only be suppressed on structs, classes, and enums
 2 | }
 3 | 

Both.swift:8:1: error: cannot both conform to and suppress conformance to 'Sendable'
 6 | }
 7 | 
 8 | extension Container: Sendable {}
   | `- error: cannot both conform to and suppress conformance to 'Sendable'
 9 | 
10 | protocol IsolatedProtocol: Sendable {

Both.swift:13:8: error: cannot both conform to and suppress conformance to 'Sendable'
11 | }
12 | 
13 | struct Test: IsolatedProtocol, ~Sendable {
   |        `- error: cannot both conform to and suppress conformance to 'Sendable'
14 | }
15 | 

Both.swift:20:7: error: cannot both conform to and suppress conformance to 'Sendable'
18 | }
19 | 
20 | class Refined: IsolatedBase, ~Sendable {
   |       `- error: cannot both conform to and suppress conformance to 'Sendable'
21 | }
22 | 

네 곳이 모두 오류이고 메시지는 둘로 갈린다.

  • actor(1번 줄): actor 는 늘 Sendable 이라서 억제할 수 없다. 6.4 는 이것을 “struct, class, enum 에서만 억제할 수 있다” 는 오류로 막는다
  • extension 으로 다시 붙이기(8번 줄): 억제한 타입에 Sendable 을 extension 으로 되붙일 수 없다. allevato 가 #22 에서 ~BitwiseCopyable 로 보여 준 것과 같다
  • 프로토콜로 물려받기(13번 줄): IsolatedProtocol 이 Sendable 을 상속하므로 그 프로토콜을 따르는 순간 Sendable conformance 를 받는다. 억제와 부딪힌다
  • global actor 클래스를 상속(20번 줄): @MainActor 클래스는 Sendable 이다(SE-0434 글). 그 클래스를 물려받은 하위 클래스에서 억제하면 부딪힌다

jamieQ 는 pitch #40 에서 이 경계를 직접 재서 올렸다. @MainActor 프로토콜이 Sendable 을 상속하는 경로와 actor A: ~Sendable 이 오류 없이 통과하는 버그를 짚은 것이다. xedin 은 #41 에서 ~Sendable 이 ~BitwiseCopyable 용 인프라 위에 지어져서 빠진 경우가 있을 수 있다고 하고, actor 와 프로토콜 경로를 본문에 쓰고 마지막 경우는 막겠다고 답했다. jamieQ 의 코드 중 @MainActor 프로토콜 경로는 6.4 에서 이렇게 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
@MainActor
protocol GAITRefineSendable: Sendable {}

@MainActor
class InferredFromGAIT: ~Sendable {}

class InferredFromRefinedGAITProto: ~Sendable, GAITRefineSendable {}

func takeSendable(_: some Sendable) {}

func g(_ a: InferredFromGAIT) {
    takeSendable(a)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
GA.swift:7:7: error: cannot both conform to and suppress conformance to 'Sendable'
 5 | class InferredFromGAIT: ~Sendable {}
 6 |
 7 | class InferredFromRefinedGAITProto: ~Sendable, GAITRefineSendable {}
   |       `- error: cannot both conform to and suppress conformance to 'Sendable'
 8 |
 9 | func takeSendable(_: some Sendable) {}

GA.swift:12:5: error: type 'InferredFromGAIT' does not conform to the 'Sendable' protocol
 3 |
 4 | @MainActor
 5 | class InferredFromGAIT: ~Sendable {}
   |       `- note: class 'InferredFromGAIT' explicitly suppresses conformance to 'Sendable' protocol
 6 |
 7 | class InferredFromRefinedGAITProto: ~Sendable, GAITRefineSendable {}
   :
10 |
11 | func g(_ a: InferredFromGAIT) {
12 |     takeSendable(a)
   |     `- error: type 'InferredFromGAIT' does not conform to the 'Sendable' protocol
13 | }
14 |

두 줄에서 읽을 것이 있다. 첫째, jamieQ 가 “통과하는 버그” 로 표시했던 InferredFromRefinedGAITProto 는 6.4 에서 오류다. 둘째, @MainActor class InferredFromGAIT: ~Sendable 선언 자체는 허용된다. 선언에는 오류가 없고, takeSendable(a) 에서만 InferredFromGAIT 가 Sendable 이 아니라는 오류가 난다. @MainActor 가 붙은 클래스는 보통 Sendable 이지만 ~Sendable 을 직접 달면 그 추론이 꺼진다. global actor 에 격리된 클래스를 일부러 Sendable 이 아니게 만들 일은 드물지만, 문법은 이를 막지 않는다. Sendable 로 오해하지 않도록 note 가 억제를 명시해 준다.

한 가지 더 있다. 직접 적는 경우도 재 본다. struct Both: ~Sendable, Sendable {} 가 첫 줄이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Both: ~Sendable, Sendable {}

struct Twice: ~Sendable, @unchecked Sendable {}

struct Later: ~Sendable {}
extension Later: @unchecked Sendable {}

public class NonSendable {}

public enum ExecutionResult: ~Sendable {
    case success
    case failure(NonSendable)
}
1
2
3
4
5
Direct.swift:1:8: error: cannot both conform to and suppress conformance to 'Sendable'
 1 | struct Both: ~Sendable, Sendable {}
   |        `- error: cannot both conform to and suppress conformance to 'Sendable'
 2 |
 3 | struct Twice: ~Sendable, @unchecked Sendable {}

오류는 첫 줄 하나뿐이다. ~Sendable 과 Sendable 을 나란히 적은 Both 가 막힌다. 반면 Twice 처럼 ~Sendable 과 @unchecked Sendable 을 같이 적는 것과, Later 처럼 선언에서 억제하고 extension 에서 @unchecked Sendable 을 다는 것은 진단 없이 통과했다. 6.4 에서 @unchecked Sendable 은 억제와 부딪히는 conformance 로 취급되지 않는다는 측정이다. 그렇다면 이 줄들이 Sendable 자리에서 어떻게 움직이는지도 잰다.

1
2
3
4
5
6
7
8
9
10
11
func takesSendable<T: Sendable>(_: T) {}
struct Twice: ~Sendable, @unchecked Sendable {}
struct Later: ~Sendable {}
extension Later: @unchecked Sendable {}
class A: ~Sendable {}
final class B: A, @unchecked Sendable {}
func run() {
    takesSendable(Twice())
    takesSendable(Later())
    takesSendable(A())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
Tw.swift:10:5: error: type 'A' does not conform to the 'Sendable' protocol
 3 | struct Later: ~Sendable {}
 4 | extension Later: @unchecked Sendable {}
 5 | class A: ~Sendable {}
   |       `- note: class 'A' explicitly suppresses conformance to 'Sendable' protocol
 6 | final class B: A, @unchecked Sendable {}
 7 | func run() {
 8 |     takesSendable(Twice())
 9 |     takesSendable(Later())
10 |     takesSendable(A())
   |     `- error: type 'A' does not conform to the 'Sendable' protocol
11 | }
12 |

진단은 10번 줄의 A() 하나뿐이다. Twice 와 Later 는 Sendable 자리를 통과한다. 둘 다 ~Sendable 이 추론만 끄고, 명시한 @unchecked Sendable 은 그대로 살아 있다는 뜻이다. ~Sendable 만 단 A 는 note 가 “conformance 를 명시적으로 억제했다” 고 알려 주며 막힌다. 마지막 ExecutionResult 는 제안서 Proposed Solution 의 예인데, associated value 로 non-Sendable 타입을 가진 public enum 을 ~Sendable 로 표시해도 진단이 없다.


조건부 Sendable

pitch 에서 가장 값진 대화 하나가 여기서 나왔다. pitch 의 초안은 extension Container: Sendable where T: Sendable {} 도 오류로 두었다. Slava_Pestov 가 #23 에서 Copyable 이 그렇게 하지 않는다는 점을 짚었다. struct G<T: ~Copyable>: ~Copyable {} 와 extension G: Copyable where T: Copyable {} 는 허용된다. 선언에서 ~Copyable 을 쓰든 말든 extension 이 암묵적인 무조건 conformance 를 대체한다는 것이다. 그러니 ~Sendable 도 같아야 한다고 했다. xedin 은 #24 에서 BitwiseCopyable 만 보고 Copyable 을 보지 못했다며 허용하겠다고 했다. 제안서의 “Conditional conformances to Sendable protocol are still allowed” 문장이 이 대화의 결과다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func takesSendable<T: Sendable>(_: T) {}

struct Container<T>: ~Sendable {
    let value: T
}

extension Container: Sendable where T: Sendable {}

class Ref {}

func run() {
    takesSendable(Container(value: 1))
    takesSendable(Container(value: Ref()))
}
1
2
3
4
5
6
7
8
9
10
11
12
Conditional.swift:13:5: error: type 'Ref' does not conform to the 'Sendable' protocol
 7 | extension Container: Sendable where T: Sendable {}
 8 | 
 9 | class Ref {}
   |       `- note: class 'Ref' does not conform to the 'Sendable' protocol
10 | 
11 | func run() {
12 |     takesSendable(Container(value: 1))
13 |     takesSendable(Container(value: Ref()))
   |     `- error: type 'Ref' does not conform to the 'Sendable' protocol
14 | }
15 |

선언에서 ~Sendable 로 억제하고 extension 에서 조건부로 되살린 Container 는 Int 를 담으면 통과하고, non-Sendable 클래스 Ref 를 담으면 오류다. 오류의 주어가 Container<Ref> 가 아니라 Ref 라는 점에 주목한다. 컴파일러는 조건 T: Sendable 을 풀다가 Ref 에서 멈췄다.

제안서는 이 조합이 필요한 이유를 이렇게 설명한다. 추론이라면 무조건 Sendable 이 되었을 타입(저장 속성이나 isolation 이 그것을 허락하는 경우)에서, 작성자가 “조건부로만 Sendable” 이라고 못 박고 싶을 때 쓴다. 이미 조건부 Sendable 인 타입에는 ~Sendable 이 필요 없다. 감사 진단 ExplicitSendable 도 조건부 conformance 가 있는 타입은 이미 표시한 것으로 본다. ksluder 의 플랫폼별 감사 질문에 xedin 이 #7 에서 “~Sendable 인 타입도 조건부 Sendable 은 된다” 고 답한 것이 이 경우다.

Slava_Pestov 의 말이 정말 그런지 따로 잰다. 조건부 extension 만 있는 Phantom, 거기에 ~Sendable 까지 단 Phantom2, extension 없이 T 를 쓰지도 않는 Phantom3 를 같은 Ref 로 넣는다.

1
2
3
4
5
6
7
8
9
10
11
12
func takesSendable<T: Sendable>(_: T) {}
class Ref {}
struct Phantom<T> { let id: Int }
extension Phantom: Sendable where T: Sendable {}
struct Phantom2<T>: ~Sendable { let id: Int }
extension Phantom2: Sendable where T: Sendable {}
struct Phantom3<T> { let id: Int }
func run() {
    takesSendable(Phantom<Ref>(id: 1))
    takesSendable(Phantom2<Ref>(id: 1))
    takesSendable(Phantom3<Ref>(id: 1))
}
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
Ph.swift:9:5: error: type 'Ref' does not conform to the 'Sendable' protocol
 1 | func takesSendable<T: Sendable>(_: T) {}
 2 | class Ref {}
   |       `- note: class 'Ref' does not conform to the 'Sendable' protocol
 3 | struct Phantom<T> { let id: Int }
 4 | extension Phantom: Sendable where T: Sendable {}
   :
 7 | struct Phantom3<T> { let id: Int }
 8 | func run() {
 9 |     takesSendable(Phantom<Ref>(id: 1))
   |     `- error: type 'Ref' does not conform to the 'Sendable' protocol
10 |     takesSendable(Phantom2<Ref>(id: 1))
11 |     takesSendable(Phantom3<Ref>(id: 1))

Ph.swift:10:5: error: type 'Ref' does not conform to the 'Sendable' protocol
 1 | func takesSendable<T: Sendable>(_: T) {}
 2 | class Ref {}
   |       `- note: class 'Ref' does not conform to the 'Sendable' protocol
 3 | struct Phantom<T> { let id: Int }
 4 | extension Phantom: Sendable where T: Sendable {}
   :
 8 | func run() {
 9 |     takesSendable(Phantom<Ref>(id: 1))
10 |     takesSendable(Phantom2<Ref>(id: 1))
   |     `- error: type 'Ref' does not conform to the 'Sendable' protocol
11 |     takesSendable(Phantom3<Ref>(id: 1))
12 | }

Phantom 과 Phantom2 는 ~Sendable 이 있든 없든 똑같이 Ref 에서 오류가 나고, extension 이 없는 Phantom3 는 T 를 저장하지 않아서 무조건 Sendable 로 추론되어 Ref 를 넣어도 통과한다. 명시한 조건부 conformance 가 이미 암묵적인 무조건 conformance 를 대체하고 있다는 뜻이다. 그래서 이미 조건부 Sendable 인 타입에는 ~Sendable 이 필요 없고, ~Sendable 을 더해도 달라지는 것이 없다. Slava_Pestov 가 Copyable 에서 짚은 구조가 Sendable 에서도 그대로 재현된다.


public API 감사

이 제안의 동기였던 감사를 실제로 돌려 본다. 공개 API 일곱 종류를 한 파일에 둔다.

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
public struct Implicit {
    public let id: Int
}

public struct Marked: Sendable {
    public let id: Int
}

public struct Suppressed: ~Sendable {
    public let id: Int
}

public class OldStyle {
}

@available(*, unavailable)
extension OldStyle: Sendable {}

public struct Generic<T> {
    public let value: T
}

extension Generic: Sendable where T: Sendable {}

public class Plain {
}

struct Internal {
    let id: Int
}

기본 설정에서는 진단이 하나도 없다. 감사 진단은 꺼져 있는 진단 그룹이다. -Wwarning ExplicitSendable 로 켠다.

1
bash diag.sh -Wwarning ExplicitSendable Audit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Audit.swift:1:15: warning: public struct 'Implicit' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
 1 | public struct Implicit {
   |               |- warning: public struct 'Implicit' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
   |               |- note: consider making struct 'Implicit' conform to the 'Sendable' protocol
   |               |- note: consider suppressing conformance to 'Sendable' protocol
   |               `- note: make struct 'Implicit' explicitly non-Sendable to suppress this warning
 2 |     public let id: Int
 3 | }

Audit.swift:25:14: warning: public class 'Plain' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
23 | extension Generic: Sendable where T: Sendable {}
24 | 
25 | public class Plain {
   |              |- warning: public class 'Plain' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
   |              |- note: consider suppressing conformance to 'Sendable' protocol
   |              `- note: make class 'Plain' explicitly non-Sendable to suppress this warning
26 | }
27 |

[#ExplicitSendable]: <https://docs.swift.org/compiler/documentation/diagnostics/explicit-sendable-annotations>

일곱 타입 중 경고는 두 곳뿐이다. 표시가 없는 Implicit 과 Plain 이다. 나머지 다섯은 의도가 코드에 적혀 있어서 조용하다.

타입표시감사 결과
Implicit없음경고
MarkedSendable조용
Suppressed~Sendable조용
OldStyleunavailable extension조용
Generic조건부 Sendable조용
Plain (class)없음경고
Internal없음, internal조용

note 가 길을 안내하는 모양도 보인다. struct 인 Implicit 에는 note 가 셋이다. “Sendable 로 만들어 보라”, “억제해 보라”, “명시적으로 non-Sendable 으로 만들면 이 경고가 사라진다”. 이 note 들은 fix-it 을 달고 있다. -serialize-diagnostics 로 받은 진단에서 읽으면 첫째 note 는 : Sendable 을, 둘째 note 는 : ~Sendable 을 넣고, 셋째 note 는 @available(*, unavailable) 줄과 extension Implicit: Sendable { } 를 넣는다. 셋째는 6.4 에서도 옛 방식이다. class 인 Plain 에는 첫째 note 가 없다. 이것이 class 라서인지 따로 잰다.

1
2
3
4
5
6
7
8
public final class FC { public let x: Int = 0 }
public struct HoldsRef { let r: FC2 }
public class FC2 {}
@frozen public struct Fr { public let id: Int }
public enum E { case a, b }
public actor Ac {}
@MainActor public class MC {}
public protocol PP {}
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
Au2.swift:1:20: warning: public class 'FC' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
1 | public final class FC { public let x: Int = 0 }
  |                    |- warning: public class 'FC' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
  |                    |- note: consider making class 'FC' conform to the 'Sendable' protocol
  |                    |- note: consider suppressing conformance to 'Sendable' protocol
  |                    `- note: make class 'FC' explicitly non-Sendable to suppress this warning
2 | public struct HoldsRef { let r: FC2 }
3 | public class FC2 {}

Au2.swift:2:15: warning: public struct 'HoldsRef' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
1 | public final class FC { public let x: Int = 0 }
2 | public struct HoldsRef { let r: FC2 }
  |               |- warning: public struct 'HoldsRef' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
  |               |- note: consider suppressing conformance to 'Sendable' protocol
  |               `- note: make struct 'HoldsRef' explicitly non-Sendable to suppress this warning
3 | public class FC2 {}
4 | @frozen public struct Fr { public let id: Int }

Au2.swift:3:14: warning: public class 'FC2' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
1 | public final class FC { public let x: Int = 0 }
2 | public struct HoldsRef { let r: FC2 }
3 | public class FC2 {}
  |              |- warning: public class 'FC2' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
  |              |- note: consider suppressing conformance to 'Sendable' protocol
  |              `- note: make class 'FC2' explicitly non-Sendable to suppress this warning
4 | @frozen public struct Fr { public let id: Int }
5 | public enum E { case a, b }

Au2.swift:5:13: warning: public enum 'E' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
3 | public class FC2 {}
4 | @frozen public struct Fr { public let id: Int }
5 | public enum E { case a, b }
  |             |- warning: public enum 'E' does not specify whether it is 'Sendable' or not [#ExplicitSendable]
  |             |- note: consider making enum 'E' conform to the 'Sendable' protocol
  |             |- note: consider suppressing conformance to 'Sendable' protocol
  |             `- note: make enum 'E' explicitly non-Sendable to suppress this warning
6 | public actor Ac {}
7 | @MainActor public class MC {}

[#ExplicitSendable]: <https://docs.swift.org/compiler/documentation/diagnostics/explicit-sendable-annotations>

class 라서 note 가 빠지는 것이 아니다. final 이고 저장 속성이 let 인 FC 는 “Sendable 로 만들어 보라” note 를 받는다. 같은 모양의 final 이 아닌 class 는 받지 못한다. 따로 재 보니 속성이 없는 public final class 와 var 를 가진 public final class 도 이 note 를 받았고, final 이 아닌 public class 는 let 속성이 있어도 받지 못했다. 앞의 Plain 이 note 를 받지 못한 것은 final 이 아니기 때문이다. struct 도 마찬가지로 저장 속성이 놓인 모양에 달려 있다. non-Sendable 인 FC2 를 저장 속성으로 가진 HoldsRef 는 struct 인데도 첫째 note 가 없고, case 만 있는 enum E 는 받는다. 컴파일러가 “이 타입에는 Sendable 을 달 수 있다” 고 볼 수 있는 모양일 때만 첫째 note 를 권한다는 정리다.

감사에서 조용한 타입도 하나 더 있다. Fr(@frozen public struct), Ac(public actor), MC(@MainActor public class), PP(public protocol)는 경고가 없다. @frozen public struct 와 actor 와 @MainActor 클래스는 이미 Sendable 이어서 표시할 것이 없고, protocol 은 conformance 를 갖는 타입이 아니라서 감사 대상이 아니다.

-Wwarning 대신 -Werror 를 쓰면 같은 두 곳이 error 가 되고 exit code 는 1 이다.

1
bash diag.sh -Werror ExplicitSendable Audit.swift
1
Audit.swift:1:15: error: public struct 'Implicit' does not specify whether it is 'Sendable' or not [#ExplicitSendable]

(위 출력은 첫 줄만 옮긴 것이다. 두 번째 오류는 25번 줄의 Plain 이다.) 라이브러리 CI 에서 이 그룹을 error 로 두면 표시 없는 public 타입이 새로 들어올 때 빌드가 멈추게 된다.

옛 플래그 -require-explicit-sendable 은 6.4 에서 단독으로 주면 같은 파일에서 진단이 나오지 않았다. -swift-version 5 를 붙여도, -enable-library-evolution 을 붙여도 마찬가지다. 플래그 자체는 --help-hidden 에 “Require explicit Sendable annotations on public declarations” 로 남아 있다. 6.4 에서 감사를 켜는 방법은 -Wwarning ExplicitSendable 이다.

이 그룹의 이름을 두고 pitch 스레드에서 현장 문제가 하나 더 나왔다. ethanhuang13 이 #25 에서 진단 문서 사이트에는 ExplicitSendable 이 올라와 있는데 swift build -Xswiftc -Wwarning -Xswiftc ExplicitSendable 은 “unknown warning group” 경고를 낸다고 했다. xedin 은 #26 에서 main 브랜치 스냅숏에만 있고 6.2 에서는 -require-explicit-sendable 을 쓰라고 답했다. ethanhuang13 은 #28 에서 문서가 version 을 구분하지 않아 기능이 이미 나온 것처럼 보인다고 지적했다. Joseph_Heck 은 #35 에서 이 사이트가 main 브랜치 기준으로 거의 매일 갱신되는 오래된 문제이고, 문서화 workgroup 과 웹사이트 workgroup 이 버전별 문서를 준비하는 중이라고 설명했다. 위의 -require-explicit-sendable 측정은 이 이야기와 맞물린다. 6.4 에서는 ExplicitSendable 그룹이 정식 경로가 되었고 옛 플래그만으로는 경고가 나오지 않는다.


unavailable extension 과 ~Sendable 의 비교

두 표기를 나란히 정리한다. 앞에서 잰 것이 대부분이고, 새로 잴 것은 하나다. unavailable extension 은 타입과 다른 파일에 둘 수 있고 플랫폼별 @available 로도 쓸 수 있다. 파일 두 개로 재 본다. 첫 파일은 타입만 선언하고 둘째 파일이 extension 을 단다.

1
2
3
4
5
6
7
8
// X.swift
public class X {}

// Y.swift
@available(macOS, unavailable)
extension X: Sendable {}
func takes<T: Sendable>(_: T) {}
func run() { takes(X()) }
1
2
3
4
5
6
7
8
Y.swift:4:14: error: conformance of 'X' to 'Sendable' is unavailable in macOS
1 | @available(macOS, unavailable)
2 | extension X: Sendable {}
  | `- note: conformance of 'X' to 'Sendable' has been explicitly marked unavailable here
3 | func takes<T: Sendable>(_: T) {}
4 | func run() { takes(X()) }
  |              `- error: conformance of 'X' to 'Sendable' is unavailable in macOS
5 |

다른 파일에 둔 extension 도, macOS 에서만 unavailable 인 표시도 통과한다. 이 두 가지는 ~Sendable 로 할 수 없다. 표로 모으면 이렇다.

비교unavailable extension~Sendable
하위 클래스물려받는다. @unchecked Sendable 하위 클래스에 경고와 오류 (Old.swift)물려받지 않는다. @unchecked Sendable 하위 클래스가 통과 (AB.swift)
쓸 수 있는 자리extension 이라 다른 파일에 둘 수 있고 @available(macOS, unavailable) 처럼 플랫폼별로 쓸 수 있다타입 선언의 상속 절만. extension 은 오류 (Errors.swift)
ExplicitSendable 감사표시한 것으로 본다 (OldStyle)표시한 것으로 본다 (Suppressed)
인터페이스$TildeSendable 가드 없이 @available(*, unavailable) extension ... : Swift::Sendable 로 찍힌다#if compiler(>=5.3) && $TildeSendable 가드로 감싸진다
감사 경고의 fix-it셋째 note 가 @available(*, unavailable) 과 extension X: Sendable { } 를 넣는다둘째 note 가 : ~Sendable 을 넣는다

고르는 기준은 하위 클래스다. 하위 클래스에 @unchecked Sendable 을 열어 둘 필요가 있으면 ~Sendable 뿐이다. 플랫폼마다 non-Sendable 이어야 하는 범위가 다른 것은 ksluder 가 원했던 쓰임이고, 이 경우는 ~Sendable 대신 조건부 Sendable 으로 푼다. 감사 진단의 note 는 이 차이를 가르쳐 주지 않는다. 셋째 note 의 fix-it 이 6.4 에서도 unavailable extension 을 넣기 때문에, 하위 클래스를 열어 둘 class 작성자는 셋째가 아니라 둘째 note 를 골라야 한다.


스레드에서 오간 이야기

pitch 는 41개 글, 리뷰는 12개 글(마지막 #12 는 John_McCall 의 글이고 내용이 비어 있다), 수락 공지는 한 글이다. 이야기는 크게 세 줄기다. 이 표기를 어디까지 허용할 것인가, 다른 ~ 프로토콜과 얼마나 같게 만들 것인가, 현장 도구가 이것을 받아낼 수 있는가.


pitch 스레드

문법의 경계를 두고 오간 이야기는 앞에서 한 절씩 나눠 소개했다. 그 흐름을 한 번 더 정리한다.

  • xwu #2 와 xedin #3: 제네릭 매개변수의 ~Sendable 은 무의미한데 오류여야 하느냐. ~BitwiseCopyable 과 맞추려는 것이고 경고도 가능하다. 6.4 는 오류다
  • jmschonfeld #4 와 xedin #5: Foundation 의 현장 사정, 그리고 extension 에는 쓸 수 없다
  • Slava_Pestov #6 와 xedin #7: non-public 타입의 암묵적 Sendable 추론 자체를 upcoming feature 로 없애자. 범위 밖이고 소스 호환에 영향이 있다
  • 8675309 #14, #20 과 xedin #19, #21, allevato #22: “추론을 끈다” 와 “따르지 않는다” 의 차이. 구체 타입에서는 같다
  • Slava_Pestov #23 과 xedin #24: 조건부 Sendable 허용의 계기
  • FranzBusch #15 와 xedin #16: -require-explicit-sendable 이 이 제안과 같이 쓰이고 진단 그룹 ExplicitSendable 이 되었다
  • grynspan #27: 추론되는 모든 conformance 로 넓히자. Copyable, Escapable 과 최대한 같게 만들자는 요청이다. xwu 가 #32 에서 Equatable, Hashable, RawRepresentable 을 말하느냐고 되물었고 이 이야기가 Future Directions 가 되었다
  • jamieQ #40 과 xedin #41: global actor 와 프로토콜 경로의 빈틈

그리고 사소하지만 분위기를 보여 주는 대목이 있다. jamieQ 가 #11 에서 제안서 예제의 주석이 무슨 뜻이냐고 물었고, xedin 이 #12 에서 “because” 를 “before” 로 고쳐야 한다고 답했다. pitch 첫 글의 그 주석은 Sendable 로 추론될 수 있어도 추론하지 않는다는 뜻의 문장이었는데 “because” 때문에 문장이 이어지지 않았다. 최종 제안서에는 이 주석이 없다. Detailed Design 에는 // Suppress Sendable inference 라는 주석을 단 struct NotSendableType: ~Sendable { let data: String } 가 있고, Proposed Solution 은 ExecutionResult 와 Base 를 예로 든다.


리뷰 스레드

리뷰는 조용했고 방향이 거의 한쪽이었다. jmschonfeld 의 #3, KeithBauerANZ 의 #4, ktoso 의 #9 가 찬성이었다. jmschonfeld 는 여러 곳에서 쓰겠다며 반겼다.

  • ksluder #2, #6 과 xedin #5, #7: 플랫폼별 감사. 조건부 Sendable 로 해결한다
  • jmschonfeld #3: Foundation 의 -require-explicit-sendable 과 Objective-C. “후속 방향” 절에서 다룬다
  • vanvoorden #8: actor 가 조건부로만 Sendable 이어야 하는 아주 드문 경우를 Alternatives 에서 한 번 짚어 달라
  • grynspan #10: <T: ~Sendable> 은 no-op 이어도 허용하는 편이 일관된다. 반대 의견이 아니라 사소한 지적이라고 스스로 말했다

수락

xwu 는 2026-03-17 수락 공지(#1)에서 리뷰가 2026-03-16 에 끝났고 언어 steering group 이 제안을 accept 했다고 알렸다. 수정 사항은 언급되지 않았다. 같은 날 리뷰 스레드 #11 에서도 같은 결정을 알렸다.


기대 효과

  • 감사의 결과가 소스에 남는다. 지금까지는 “Sendable 표시가 없다” 가 “점검 전” 인지 “점검 후 non-Sendable” 인지 가릴 수 없었다. ~Sendable 이 후자를 적는 자리가 되어, ExplicitSendable 경고가 0이면 공개 타입 전부가 점검 상태가 된다
  • 하위 클래스의 길이 열린다. 부모가 non-Sendable 이고 일부 하위 클래스만 스레드 안전한 프레임워크 구조(Foundation, 서버 쪽 라이브러리)에서, 부모에 표시를 하면서 @unchecked Sendable 하위 클래스를 허용할 수 있다
  • 표기가 짧아진다. Sendable 을 붙이고 unavailable 로 막고 구버전 컴파일러용 #if 를 두르던 세 줄이 한 줄로 줄어든다. dnadoba 가 스니펫까지 만들었던 불편이다
  • 오류 메시지가 의도를 전한다. 억제한 타입을 Sendable 자리에 넣으면 note 가 “이 struct 가 conformance 를 명시적으로 억제했다” 고 말해서, 사용자가 Sendable 을 붙여 보려는 헛수고를 줄인다
  • 다른 ~ 프로토콜과 문법이 하나로 모인다. ~Copyable, ~Escapable, ~BitwiseCopyable 에서 익힌 “구체 타입의 선언에서 추론을 끈다” 가 Sendable 에도 통한다

다른 선택지는 왜 안 됐나

제안서가 따로 검토한 대안은 하나이고, 스레드에서 몇 가지가 더 나왔다.


nonSendable 속성

제안서 Alternatives Considered 의 유일한 항목이다.

1
2
3
4
@nonSendable
struct MyType {
    let value: Int
}

제안서의 이유는 짧다. conformance 쪽이 반대 경우(이 타입이 Sendable 이다)와 나란히 쓰기에 더 편하고, 다른 marker protocol 의 억제 관례(~Copyable 등)를 따른다는 것이다. 속성이라면 Sendable 을 붙이는 방법과 떼는 방법이 서로 다른 문법 영역에 놓이게 된다.


extension 에 쓰기

jmschonfeld 가 pitch #4 에서 물었고 ksluder 가 리뷰 #2 에서 플랫폼별 감사를 위해 원했다. 제안서가 막은 이유는 “기존 코드의 의미를 바꿀 위험” 이다. 앞의 Errors.swift 2번 줄이 실제 오류다. xedin 의 해법은 원하는 플랫폼에서만 조건부 Sendable 으로 만들면 나머지는 자동으로 non-Sendable 이 되므로 ~Sendable 이 필요 없다는 것이다(리뷰 #5, #7).


제네릭 매개변수에 허용하기

xwu 의 pitch #2 와 grynspan 의 리뷰 #10 이 주장했다. <T: ~Sendable> 은 <T> 와 같은 뜻이라 허용해도 해가 없다는 입장이다. xedin 은 ~BitwiseCopyable 과 맞추려는 것이라고 했다. 최종안은 오류를 유지했고, 6.4 측정에서도 오류다.


non-public 추론 폐지

Slava_Pestov 가 pitch #6 에서 non-public 타입의 암묵적 Sendable 추론을 upcoming feature 로 없애는 것을 Alternatives 에 넣자고 했다. xedin 은 #7 에서 소스 호환성에 영향이 있는 별개의 주제라고 답했다. 이 제안은 추론을 건드리지 않고 끄는 도구만 더한다.


actor 의 조건부 Sendable

vanvoorden 이 리뷰 #8 에서 actor 가 조건부로만 Sendable 이어야 하는 경우를 Alternatives 에서 다뤄 달라고 했다. 제안서는 actor 를 늘 Sendable 이라고 두었고, 6.4 에서 actor A: ~Sendable 은 앞의 Both.swift 1번 줄의 오류다.


Swift 6 모드와 마이그레이션

소스 호환, API resilience, ABI 를 나눠 본다.


소스 호환

제안서의 Source Compatibility 는 이 변경이 순수한 추가이고 기존 코드의 Sendable 추론을 바꾸지 않는다고 말한다. 새 문법을 쓰지 않으면 달라질 것이 없다. 이미 쓴 코드에서 바꿀 수 있는 것은 두 가지다. 하나는 unavailable extension 을 ~Sendable 로 옮기는 것이다. 제안서 API Resilience 절은 이것이 소스 호환이 되는 옮김이라고 적는다. 앞의 Old.swift(unavailable extension 을 붙인 Base 와 ThreadSafe)와 AB.swift(~Sendable 을 단 A 와 B)를 비교하면 그 옮김이 하위 클래스의 경고와 오류를 지우는 것을 볼 수 있다. 같은 구조에서 부모의 unavailable extension 을 ~Sendable 로 바꾸면 ThreadSafe 의 경고가 사라지고 takesSendable 이 통과한다. 반대 방향은 없다. ~Sendable 을 다시 unavailable 로 돌리는 것은 하위 클래스의 @unchecked Sendable 을 깬다.

다른 하나는 이미 Sendable 이던 타입을 ~Sendable 로 바꾸는 것이다. 제안서는 이것을 source breaking 이라고 적는다. Sendable 이라고 약속한 타입을 이 약속에서 빼는 것이므로, 그 약속에 기댄 클라이언트가 앞의 Basic.swift 와 같은 오류를 만난다.

다만 이 말은 Sendable 로 추론되지 않던 public 타입의 이야기다. 이미 추론된 @frozen public struct 에 ~Sendable 을 나중에 달면 source breaking 이다. 인터페이스에도 그 conformance 가 찍혀 있기 때문이다(뒤의 “인터페이스 파일” 절). 라이브러리 L 에 세 타입을 두고 클라이언트 C 에서 쓴다.

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
// L.swift
@frozen public struct FrozenPlain {
    public let id: Int
    public init(id: Int) { self.id = id }
}

@frozen public struct FrozenSup: ~Sendable {
    public let id: Int
    public init(id: Int) { self.id = id }
}

public struct NF {
    public let id: Int
    public init(id: Int) { self.id = id }
}

// C.swift
import L

func processData<T: Sendable>(_ data: T) { }

func run() {
    processData(FrozenPlain(id: 1))
    processData(FrozenSup(id: 1))
    processData(NF(id: 1))
}
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
C.swift:7:5: error: type 'FrozenSup' does not conform to the 'Sendable' protocol
 5 | func run() {
 6 |     processData(FrozenPlain(id: 1))
 7 |     processData(FrozenSup(id: 1))
   |     `- error: type 'FrozenSup' does not conform to the 'Sendable' protocol
 8 |     processData(NF(id: 1))
 9 | }

/Users/dongik/se518/fz/L.swift:6:23: note: struct 'FrozenSup' explicitly suppresses conformance to 'Sendable' protocol
 4 | }
 5 |
 6 | @frozen public struct FrozenSup: ~Sendable {
   |                       `- note: struct 'FrozenSup' explicitly suppresses conformance to 'Sendable' protocol
 7 |     public let id: Int
 8 |     public init(id: Int) { self.id = id }

C.swift:8:5: error: type 'NF' does not conform to the 'Sendable' protocol
 6 |     processData(FrozenPlain(id: 1))
 7 |     processData(FrozenSup(id: 1))
 8 |     processData(NF(id: 1))
   |     `- error: type 'NF' does not conform to the 'Sendable' protocol
 9 | }
10 |

/Users/dongik/se518/fz/L.swift:11:15: note: struct 'NF' does not conform to the 'Sendable' protocol
 9 | }
10 |
11 | public struct NF {
   |               `- note: struct 'NF' does not conform to the 'Sendable' protocol
12 |     public let id: Int
13 |     public init(id: Int) { self.id = id }

FrozenPlain 은 클라이언트에서 통과하고, 같은 모양에 ~Sendable 을 단 FrozenSup 은 7번 줄에서 오류다. 이미 배포한 @frozen 타입에 ~Sendable 을 뒤늦게 달면 클라이언트가 이 오류를 만난다. 8번 줄의 NF 는 ~Sendable 이 없어도 같은 오류가 나는 타입이라 여기에 ~Sendable 을 달아도 클라이언트의 결과는 달라지지 않는다. 제안서가 말한 “public 타입에 붙여도 소스 호환이 깨지지 않는다” 는 @frozen 이 아닌 public 타입의 이야기다.

언어 모드별로 Subclass.swift 를 재 본다. 이 파일은 Old.swift 의 Base, ThreadSafe 와 AB.swift 의 A, B 를 한 파일에 합쳐서 takesSendable(B()) 와 takesSendable(ThreadSafe()) 를 함께 부른다. 진단이 나오는 쪽은 Base 에 unavailable extension 을 붙인 구성이고, 두 진단의 수준이 모드에 따라 어떻게 달라지는지 보는 것이다.

모드ThreadSafe 의 conformance 경고takesSendable(ThreadSafe())
Swift 5warningwarning (; this is an error in the Swift 6 language mode)
Swift 5 + -strict-concurrency=completewarningwarning (같은 문구)
Swift 6warningerror

선언 자리의 경고(진단 그룹 UnavailableSendableConformance)는 세 모드 모두 warning 이다. 사용 자리의 진단만 Swift 6 에서 error 로 오른다. 앞의 Basic 과 Inference2 표와 합치면 ~Sendable 의 진단은 둘로 갈린다. 선언 자리의 오류는 모드와 상관없이 error 이고, Sendable 을 요구하는 사용 자리만 “Swift 5 는 조용하고, complete 는 warning, Swift 6 은 error” 라는 Sendable 위반의 일반 규칙을 따른다. unavailable conformance 는 사용 자리도 Swift 5 에서 warning 이다.


인터페이스 파일

라이브러리는 컴파일된 모듈과 함께 .swiftinterface 텍스트로도 공개된다. 이 파일은 옛 컴파일러에서도 읽혀야 하는데, ~Sendable 을 모르는 컴파일러가 이 문법을 만나면 파싱에서 멈춘다. 앞의 Audit.swift 를 라이브러리 진화 모드로 내보내서 어떻게 찍히는지 본다.

1
xcrun swiftc -swift-version 6 -emit-module -enable-library-evolution -module-name AuditLib -emit-module-interface-path AuditLib.swiftinterface -o AuditLib.swiftmodule Audit.swift
1
2
3
4
5
6
7
8
9
#if compiler(>=5.3) && $TildeSendable
public struct Suppressed : ~Swift::Sendable {
  public let id: Swift::Int
}
#else
public struct Suppressed {
  public let id: Swift::Int
}
#endif

~Sendable 을 단 Suppressed 는 $TildeSendable 이라는 기능 검사로 감싸져 나온다. 기능을 아는 컴파일러는 ~Swift::Sendable 을 읽고, 모르는 컴파일러는 표시 없는 public struct 를 읽는다. 둘의 의미가 같은 이유는 인터페이스가 Sendable conformance 를 모두 명시해서 적기 때문이다. 인터페이스를 읽는 컴파일러는 추론을 하지 않으므로 표시가 없으면 non-Sendable 이다. 그래서 ~Sendable 을 모르는 컴파일러가 표시 없는 public struct 를 읽어도 뜻이 바뀌지 않는다. 제안서가 “public 타입에 ~Sendable 을 붙여도 소스 호환이 깨지지 않는다” 고 한 이유가 이것이다. 나머지는 그대로 나온다.

1
2
3
4
5
@available(*, unavailable)
extension AuditLib::OldStyle : Swift::Sendable {
}
extension AuditLib::Generic : Swift::Sendable where T : Swift::Sendable {
}

unavailable extension 과 조건부 Sendable 은 일반 conformance 문법이라서 감싸지 않는다.

@frozen public struct 는 사정이 다르다. 추론된 Sendable 이 인터페이스에 명시적인 extension 으로 풀려서 찍힌다. 앞의 L.swift 를 라이브러리 진화 모드로 내보내면 이렇다.

1
2
#if compiler(>=5.3) && $TildeSendable
@frozen public struct FrozenSup : ~Swift::Sendable {
1
2
3
extension L::FrozenPlain : Swift::Sendable {}
extension L::FrozenPlain : Swift::BitwiseCopyable {}
extension L::FrozenSup : Swift::BitwiseCopyable {}

추론된 FrozenPlain 은 Sendable extension 이 한 줄 찍히고, ~Sendable 인 FrozenSup 과 @frozen 이 아닌 NF 에는 Sendable 줄이 없다. 인터페이스를 읽는 쪽은 추론하지 않으므로 이 한 줄이 FrozenPlain 을 Sendable 로 만든다. 그래서 @frozen 타입에 나중에 ~Sendable 을 달면 그 줄이 사라지고 앞의 소스 호환 절에서 본 오류가 난다.


ABI

~Sendable 은 컴파일 시간에만 쓰이는 표시다. 런타임 표현도 없고 이미 컴파일된 코드에 주는 영향도 없다. 제안서의 ABI 절은 그 두 줄이 전부다.


감사 켜기

6.4 에서 라이브러리를 감사하려면 컴파일러 옵션에 -Wwarning ExplicitSendable 을 준다. 경고로 시작해서 다 정리한 뒤 -Werror ExplicitSendable 로 올려 새로운 표시 누락을 막는 순서가 자연스럽다. SwiftPM 설정으로 같은 일을 하려는 시도는 pitch #25 에서 나왔다. ethanhuang13 은 그 시점의 6.2 와 main snapshot 에서 .treatWarning("ExplicitSendable", as: .warning) 이 효과가 없다고 보고했다.


후속 방향

제안서 Future Directions 는 Sendable 하나에 집중했지만, 컴파일러가 추론하는 다른 conformance 도 ~ 로 억제할 수 있다고 적는다. 세 가지가 거론되었다.

  • Equatable 과 Hashable: Slava_Pestov 가 pitch #34 에서 payload 없는 enum 의 Equatable 과 Hashable 은 public 이어도 추론되는 점을 짚었다. Sendable 과 달리 public 타입에도 추론이 일어난다
  • RawRepresentable: Slava_Pestov 는 #34 에서 RawRepresentable 이 raw type 을 적으면 따라오는 것이라 raw type 을 적고 그 conformance 를 억제하는 것은 이상하다고, 그렇게 하면 무엇을 하게 되느냐고 되물었다. dnadoba 는 #36 에서 RawRepresentable 이 주는 Equatable 구현은 enum 판별자가 아니라 rawValue 를 쓰므로 rawValue 가 긴 String 이면 성능에서 불리하다고 했다. 그래서 ~RawRepresentable 이 있으면 == 의 합성 구현을 되찾을 수 있다. allevato 는 #37 에서 init?(rawValue:) 와 rawValue 는 합성하되 conformance 만 억제하는 형태가 되느냐고 물었고, dnadoba 가 #39 에서 그렇다고 답했다. x-sheep 이 #38 에서 rawValue 기반 Equatable 이 enum 의 고유 구현보다 우선하느냐고 묻자 dnadoba 가 그렇다 고 답했다
  • 모든 추론된 conformance: grynspan 이 #27 에서 Copyable, Escapable 과 최대한 같은 모양을 원했다. 제안서는 각 경우에 미묘한 점이 있어서 별도 제안이 필요할 수 있다고 정리한다

또 하나는 Objective-C 쪽이다. jmschonfeld 는 리뷰 #3 에서 현재의 NS_HEADER_AUDIT 매크로가 모든 선언을 unavailable extension 처럼 non-Sendable 으로 표시하고 그것을 되돌릴 방법이 없다고 했다. 하위 클래스를 막는다는 뜻이다. Objective-C API 에도 ~Sendable 을 붙일 수 있다면 표준 권장 매크로를 쓰면서 Sendable 하위 클래스를 허용할 수 있다고 한다. SE-0463 글에서 본 NS_SWIFT_NONSENDABLE 이 헤더 쪽에서 non-Sendable 을 표시하는 방법이고, ~Sendable 은 Swift 쪽의 같은 일이다. 이 두 표시가 앞으로 어떻게 이어질지는 제안서에 없고 리뷰의 미래 방향 한 줄이다.


정리

  • struct, enum, class 선언의 상속 절에 ~Sendable 을 적으면 Sendable 추론이 꺼진다. 같은 모양의 타입에서 표시 없는 Plain 은 Sendable 로 추론되어 통과하고 ~Sendable 을 단 타입은 오류다. 오류의 note 가 “이 타입이 conformance 를 명시적으로 억제했다” 고 알려 준다
  • 붙일 수 있는 자리는 타입 선언뿐이다. extension, protocol, 제네릭 매개변수, actor 는 6.4 에서 모두 오류다. 제네릭 매개변수도 경고가 아니라 오류다
  • 경계에서 ~Sendable 타입은 Sendable 의 자리에 region 분석이 서는 문턱이 된다. actor 메서드로 넘기거나 Task.detached 가 캡처하면 RegionIsolation 오류가 난다. 추론되는 Sendable 타입은 같은 자리에서 조용하다
  • unavailable extension 은 하위 클래스까지 영원히 막지만 ~Sendable 은 자기 클래스만 non-Sendable 으로 둔다. 하위 클래스는 @unchecked Sendable 로 Sendable 이 될 수 있다. 검사받는 Sendable 은 non-Sendable 부모를 가질 수 없다는 기존 규칙에 막힌다
  • ~Sendable 과 Sendable 을 직접 적거나 extension 으로 되붙이거나 프로토콜, @MainActor 슈퍼클래스로 물려받으면 “cannot both conform to and suppress” 오류다. 조건부 Sendable 은 허용되고, Container<Int> 는 통과하며 Container<Ref> 는 Ref 에서 오류가 난다
  • 감사는 -Wwarning ExplicitSendable 로 켠다. 표시 없는 public 타입만 경고하고 Sendable, ~Sendable, unavailable extension, 조건부 Sendable 은 조용하다. 옛 -require-explicit-sendable 은 6.4 에서 단독으로는 경고를 내지 않는다
  • 소스 호환은 순수한 추가다. unavailable extension 을 ~Sendable 로 옮기는 것은 호환되고, Sendable 을 ~Sendable 로 바꾸는 것은 source breaking 이다. .swiftinterface 에는 $TildeSendable 기능 검사로 감싸져 나오고 ABI 영향은 없다
  • Swift 6.4 에서 구현되었다. 6.4 는 2026-09-15 에 정식 출시되었다

관련 글

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