[SE-0418] Inferring Sendable for methods and key path literals
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0418
- 상태: Implemented (Swift 6.0)
- upcoming feature flag:
InferSendableFromCaptures(upcoming feature flag 는 다음 언어 모드에서 기본이 될 동작을 지금 미리 켜 보는 컴파일러 옵션이다. 이 기능은 Swift 6 언어 모드에서 기본으로 켜진다) - 저자: Angela Laar, Kavon Farvardin, Pavel Yaskevich
- 리뷰 매니저: Becca Royal-Gordon
- 1차 pitch: Inferring Sendable for methods (2023-08-03)
- 2차 pitch: Inferring Sendable for methods and key path literals (2023-10-23)
- 리뷰: Review (2023-12-14 시작, 2024-01-01 까지)
- 수락: Accepted (2024-01-03)
- 전제 제안서: SE-0302 (
Sendable과@Sendableclosure)
한 줄 요약
Sendable 타입의 메서드를 함수 값으로 꺼낸 것, 전역 함수와 static 메서드, 붙잡는 값이 하나도 없는 key path 리터럴은 컴파일러가 알아서 Sendable 로 본다. 예전에는 { @Sendable in S.f($0) } 처럼 closure 로 감싸거나 경고를 견뎌야 했던 자리다. 대신 non-Sendable 타입의 메서드에는 @Sendable 을 붙일 수 없게 막는다.
어떤 문제였나
Swift concurrency 에서 Sendable 은 “이 값을 다른 task 나 actor 로 넘겨도 안전하다” 는 표시이고, @Sendable 은 함수와 closure 에 붙이는 같은 뜻의 표시다. Sendable 의 자세한 설명은 SE-0412 글의 “Sendable 이란?” 과 SE-0414 글의 “isolation 경계와 Sendable 이란?” 에 있다. 이 글에 필요한 만큼만 다시 짚는다.
@Sendable 함수나 closure 의 규칙은 SE-0302 가 정했다. 함수 안에서 바깥의 값을 붙잡는 것을 capture 라고 하는데, @Sendable 함수는 Sendable 인 값만 capture 할 수 있고 var 는 복사해서만 붙잡을 수 있다. 다른 thread 로 넘어간 함수가 원본 변수를 같이 만지면 data race 가 나기 때문이다. 그래서 “붙잡는 것이 없으면 Sendable 이어도 막을 이유가 없다” 는 이야기가 이 제안서의 출발점이다.
문제는 컴파일러가 그 “붙잡는 것이 없다” 를 몇몇 자리에서 알아보지 못했다는 점이다. 메서드를 함수 값으로 꺼낸 것, 전역 함수, key path 리터럴이 그 자리다.
이 글의 모든 진단은 -emit-sil 로 뽑았다. -emit-sil 은 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계에서 나오는 진단까지 빠짐없이 낸다. 타입 검사까지만 하는 -typecheck 는 SIL 단계의 진단을 빼먹는다. 컴파일러는 Xcode 27 의 Swift 6.4 하나이고, 같은 코드를 네 가지 모드로 돌려 비교했다. 모드의 뜻은 SE-0423 글의 “Swift 언어 모드와 upcoming feature flag 란?” 에 있다.
| 이름 | 옵션 |
|---|---|
| Swift 5 | -swift-version 5 |
| Swift 5 complete | -swift-version 5 -strict-concurrency=complete |
| Swift 5 + flag | 위에 -enable-upcoming-feature InferSendableFromCaptures 를 더한 것 |
| Swift 6 | -swift-version 6 |
모든 예제는 아래 Common.swift 와 같이 컴파일한다. NonSendable 은 내용을 바꿀 수 있는 final class 라서 Sendable 이 아니고, key path 의 subscript 인자로 쓰려고 Hashable 을 따르게 했다.
1
2
3
4
5
6
final class NonSendable: Hashable {
static func == (a: NonSendable, b: NonSendable) -> Bool { a === b }
func hash(into hasher: inout Hasher) {}
}
struct Entry {}
진단은 이렇게 뽑았다. 한 파일씩 Common.swift 와 같이 컴파일한다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Unapplied.swift
-o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 파일을 최상위 코드가 없는 일반 소스 파일로 다루라는 옵션이며, -wmo 는 파일 여러 개를 한꺼번에 컴파일하라는 옵션이다.
unapplied 와 partially applied 참조란?
메서드 f 를 가진 struct S 에서 f 를 부르지 않고 이름만 쓰면 함수 값이 된다. 쓰는 방법이 두 가지다.
1
2
3
4
5
6
struct S {
func f() {}
}
let partial: () -> Void = S().f
let unapplied: (S) -> (() -> Void) = S.f
S().f 는 인스턴스를 앞에 두고 쓴 것이다. 이미 S() 를 채워 넣은 () -> Void 한 층짜리 함수라서 partially applied(일부만 적용된) 참조라고 부른다. S.f 는 타입 이름으로 쓴 것이다. “S 를 받으면 f 를 돌려주는 함수” 인 (S) -> (() -> Void) 두 층짜리 함수이고, 아직 아무 인스턴스도 적용하지 않았다는 뜻에서 unapplied 참조라고 부른다. 메서드가 “self 를 첫 인자로 받는 함수” 로 꼬리를 물고 이어지는 이 모양은 SE-0042 가 다룬 curried 방식 그대로다.
제안서는 메서드가 사실상 다음 두 함수라고 풀어서 설명한다. 바깥 함수는 obj 를 받고, 안쪽 함수는 받은 obj 를 붙잡아 두었다가 arg1 이 오면 진짜 메서드를 부른다.
1
2
3
4
5
6
7
// 제안서의 pseudo-code 를 줄인 것
func NominalType_method_partiallyAppliedTo(_ obj: NominalType) -> ((ArgType) -> ReturnType) {
let inner = { [obj] (_ arg1: ArgType) -> ReturnType in
return NominalType_method(obj, arg1)
}
return inner
}
여기서 capture 가 일어나는 곳은 inner 하나이고, 붙잡는 것은 obj 하나다. 그래서 partially applied 참조가 Sendable 이려면 obj 가 Sendable 이어야 하고, 이것은 타입이 Sendable 을 따를 때만 참이다. 바깥 함수는 아무것도 붙잡지 않는다.
Sendable 이어야 하는 층은 self 를 쥔 층 하나다. 이 그림이 이 제안서 규칙 1 과 2 를 한 번에 설명한다.
제안서 Motivation 의 예를 먼저 돌려 본다. P 는 Sendable 을 따르는 protocol 이고, g 는 @Sendable 한 unapplied 함수를 받아 새 Task 안에서 부른다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
protocol P: Sendable {
init()
}
func g<T>(_ f: @escaping @Sendable (T) -> (() -> Void)) where T: P {
Task {
let instance = T()
f(instance)()
}
}
struct S: P {
func f() {}
}
func callG() {
g(S.f)
}
S 는 P 를 따르므로 Sendable 이다. 그런데 Swift 5 모드에서 이렇게 나온다.
1
2
3
4
5
6
7
Unapplied.swift:17:7: warning: converting non-Sendable function value to '@Sendable (S) -> () -> Void' may introduce data races
15 |
16 | func callG() {
17 | g(S.f)
| `- warning: converting non-Sendable function value to '@Sendable (S) -> () -> Void' may introduce data races
18 | }
19 |
Sendable 타입의 메서드인데도 함수 값으로 꺼낸 S.f 가 Sendable 이 아니라고 본 것이다. Swift 5 complete 도 같은 warning 이고, Swift 5 + flag 와 Swift 6 은 진단이 0개다. 제안서가 보여 주는 우회는 g({ @Sendable in S.f($0) }) 처럼 Sendable closure 로 감싸는 것이었다. 의미는 같은데 글자만 늘어난다.
전역 함수에서도 생기는 같은 문제
같은 문제가 전역 함수에도 있었다. 제안서 예제는 Task<Int, Never>.detached(priority: nil, operation: doWork) 인데, 지금 SDK 에서 Task.detached 의 operation 은 @Sendable 이 아니라 sending closure 라서(SE-0430 글) 이 규칙을 보여 주지 못한다. 그래서 @Sendable 함수를 받는 runSendable 을 따로 만들었다.
1
2
3
4
5
6
7
8
9
func doWork() -> Int {
Int.random(in: 1..<42)
}
func runSendable(_ f: @escaping @Sendable () -> Int) {}
func start() {
runSendable(doWork)
}
doWork 는 바깥 변수를 하나도 붙잡지 않는 전역 함수인데, Swift 5 모드에서 이렇게 나온다.
1
2
3
4
5
6
7
Global.swift:8:15: warning: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
6 |
7 | func start() {
8 | runSendable(doWork)
| `- warning: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
9 | }
10 |
Swift 5 complete 도 같다. Swift 5 + flag 와 Swift 6 에서는 진단이 0개다.
key path 란?
key path 는 “어떤 타입에서 어떤 속성을 꺼내는 길” 을 값으로 들고 다니는 것이다. \User.name 은 User 에서 name 을 꺼내는 길이고, user[keyPath: kp] 로 그 길을 따라가서 값을 읽는다. 지도 위에 그린 경로를 지도와 따로 접어서 들고 다닌다고 보면 된다. 같은 길을 User 마다 적용할 수 있어서 sorted, map 같은 함수에 “무엇으로 정렬할지” 를 넘길 때 쓴다.
key path 의 타입은 KeyPath<Root, Value> 같은 class 다. 읽기만 되는 KeyPath, 쓰기도 되는 WritableKeyPath, 참조 타입에 쓰는 ReferenceWritableKeyPath 가 있고 모두 PartialKeyPath 와 AnyKeyPath 의 자식이다. 이 타입들이 class 이고 Sendable 이 아니라는 점이 문제의 핵심이다.
key path 안에는 subscript 인자도 들어갈 수 있다. \User.[info] 처럼 쓰면 info 값이 key path 안에 붙잡혀 있다. 그래서 key path 는 함수와 마찬가지로 “무엇을 붙잡고 있는가” 로 Sendable 여부를 따질 수 있다. 아래 그림이 이 성질을 정리한다.
key path 를 다른 task 로 넘기려면
SE-0302 는 key path 리터럴을 모두 Sendable 로 취급했다. 그래서 non-Sendable 값을 붙잡는 리터럴은 막고 warning 을 냈다. 반대로 값 한 개도 붙잡지 않은 key path 라도 타입 KeyPath<User, String> 은 Sendable 이 아니다. KeyPath 가 Sendable 을 따르지 않는 class 이기 때문이다.
그러면 key path 를 다른 task 로 넘기려는 코드는 타입에 & Sendable 을 적어야 한다. & Sendable 은 “이 타입이면서 Sendable 이기도 한 값” 이라는 합성 타입이다. 아래 코드는 두 가지 선택을 나란히 둔 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct User: Sendable {
var name = "Harold"
}
func readLater(_ kp: KeyPath<User, String>) {
Task.detached {
print(User()[keyPath: kp])
}
}
func readLaterSendable(_ kp: KeyPath<User, String> & Sendable) {
Task.detached {
print(User()[keyPath: kp])
}
}
@main struct App {
static func main() async {
readLaterSendable(\.name)
try? await Task.sleep(for: .milliseconds(100))
}
}
readLater 는 key path 를 그냥 받고, readLaterSendable 은 & Sendable 을 요구한다. main 에서 \.name 을 readLaterSendable 에 넘기는데, Swift 5 complete 의 결과는 이렇다.
1
2
3
4
5
6
7
8
9
10
11
12
13
KeyPathTask.swift:19:23: warning: type 'KeyPath<User, String>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
17 | @main struct App {
18 | static func main() async {
19 | readLaterSendable(\.name)
| `- warning: type 'KeyPath<User, String>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
20 | try? await Task.sleep(for: .milliseconds(100))
21 | }
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
key path 리터럴 \.name 이 Sendable 로 추론되지 않아서 & Sendable 인 parameter 에 넘길 수 없었다. Swift 5 + flag 에서는 이 warning 이 사라지고 Swift 6 에서도 없다.
readLater 쪽은 이야기가 다르다. kp 를 그냥 받아서 Task.detached 안으로 가져가는 코드이고, 같은 complete 실행에서 이 warning 이 같이 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
KeyPathTask.swift:6:8: warning: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure; this is an error in the Swift 6 language mode [#RegionIsolation::SendingClosureRisksDataRace]
4 |
5 | func readLater(_ kp: KeyPath<User, String>) {
6 | Task.detached {
| `- warning: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure; this is an error in the Swift 6 language mode [#RegionIsolation::SendingClosureRisksDataRace]
7 | print(User()[keyPath: kp])
| `- note: closure captures 'kp' which is accessible to code in the current isolation context
8 | }
9 | }
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
Swift 5 + flag 에도 이것은 남는다. flag 는 리터럴의 추론을 바꿀 뿐, Sendable 이 아닌 KeyPath 를 task 로 가져가는 코드를 허락하지는 않기 때문이다. Swift 6 에서는 error 가 된다.
1
KeyPathTask.swift:6:8: 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]
readLaterSendable 은 Swift 6 에서 통과한다. sending 은 SE-0430 글에서, 이 note 가 말하는 isolation context 는 SE-0414 글에서 다룬다. 결론은 이렇다. key path 를 다른 task 로 넘기려면 Sendable 이어야 하고, 리터럴은 이제 붙잡은 것이 없으면 알아서 & Sendable 이 된다.
무엇이 바뀌나
제안서는 Sendable 동작을 다섯 가지 바꾼다. 앞의 두 개와 세 번째는 “붙잡는 것이 없으면 Sendable 로 본다” 를 메서드 참조와 key path 에 적용한 것이고, 네 번째는 같은 원리를 전역 함수에 적용한 것이며, 다섯째는 반대쪽에서 구멍을 막는 규칙이다.
| 번호 | 규칙 |
|---|---|
| 1 | Sendable 타입의 메서드를 unapplied 로 참조하면 @Sendable 로 추론한다 |
| 2 | Sendable 타입의 메서드를 partially applied 로 참조하면 @Sendable 로 추론한다 |
| 3 | non-Sendable 을 붙잡지 않고 actor 에 묶인 속성을 가리키지 않는 key path 리터럴은 & Sendable 로 추론한다 |
| 4 | non-local 함수(전역 함수와 static 메서드)를 참조하면 @Sendable 로 추론한다 |
| 5 | non-Sendable 타입의 메서드에 @Sendable 을 붙이는 것을 금지한다 |
메서드 참조의 Sendable 추론
규칙 1 과 2 를 한 파일에서 돌려 본다. User 는 Sendable 이고 Account 는 내용을 바꿀 수 있는 non-Sendable class 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct User: Sendable {
var address = ""
func changeAddress(new: String, old: String) {}
}
final class Account {
var balance = 0
func deposit(_ amount: Int) { balance += amount }
}
func references() {
let unapplied: @Sendable (User) -> ((String, String) -> Void) = User.changeAddress
let partial: @Sendable (String, String) -> Void = User().changeAddress
let unappliedClass: @Sendable (Account) -> (Int) -> Void = Account.deposit
let partialClass: @Sendable (Int) -> Void = Account().deposit
_ = (unapplied, partial, unappliedClass, partialClass)
}
Swift 5 와 Swift 5 complete 는 12, 13, 14, 15 줄 모두 warning 이다. 12 줄을 예로 옮긴다.
1
2
3
4
5
6
7
Partial.swift:12:72: warning: converting non-Sendable function value to '@Sendable (User) -> (String, String) -> Void' may introduce data races
10 |
11 | func references() {
12 | let unapplied: @Sendable (User) -> ((String, String) -> Void) = User.changeAddress
| `- warning: converting non-Sendable function value to '@Sendable (User) -> (String, String) -> Void' may introduce data races
13 | let partial: @Sendable (String, String) -> Void = User().changeAddress
14 | let unappliedClass: @Sendable (Account) -> (Int) -> Void = Account.deposit
Swift 5 + flag 에서는 15 줄 하나만 warning 이다.
1
Partial.swift:15:57: warning: converting non-Sendable function value to '@Sendable (Int) -> Void' may introduce data races
Swift 6 에서는 이 줄이 error 가 되고, 나머지 세 줄은 통과한다.
1
2
3
4
5
6
7
Partial.swift:15:57: error: converting non-Sendable function value to '@Sendable (Int) -> Void' may introduce data races
13 | let partial: @Sendable (String, String) -> Void = User().changeAddress
14 | let unappliedClass: @Sendable (Account) -> (Int) -> Void = Account.deposit
15 | let partialClass: @Sendable (Int) -> Void = Account().deposit
| `- error: converting non-Sendable function value to '@Sendable (Int) -> Void' may introduce data races
16 | _ = (unapplied, partial, unappliedClass, partialClass)
17 | }
네 줄이 갈리는 모습이 앞의 그림과 맞아떨어진다. User 쪽 두 줄은 User 가 Sendable 이니 unapplied 도 partially applied 도 통과한다. Account().deposit(15 줄)은 Account() 를 붙잡은 한 층짜리 함수이고 Account 가 non-Sendable 이라 error 다. 14 줄의 Account.deposit 은 non-Sendable class 의 unapplied 참조인데도 통과한다. 바깥 층은 Account 를 받기만 할 뿐 아무것도 붙잡지 않기 때문이다.
unapplied 참조의 바깥 층과 안쪽 층
이 점은 수락 스레드에서 Nickolas_Pohilets 가 짚었다(#2). “unapplied 메서드는 전역 함수와 같아서 늘 Sendable 이고, 타입의 Sendable 여부는 결과 함수의 Sendable 여부에만 영향을 준다” 는 이야기다. hborla 는 InferSendableFromCaptures 의 구현이 이미 그렇게 동작한다고 답했다(#3). 아래는 Nickolas_Pohilets 가 든 a 와 b 에 c 를 비교용으로 덧붙여 돌려 본 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
final class A {
func foo(_ s: String) -> Bool { true }
}
struct B: Sendable {
func foo(_ s: String) -> Bool { true }
}
func check() {
let a: @Sendable (A) -> (String) -> Bool = A.foo
let b: @Sendable (B) -> @Sendable (String) -> Bool = B.foo
let c: @Sendable (A) -> @Sendable (String) -> Bool = A.foo
_ = (a, b, c)
}
Swift 6 에서 a 와 b 는 통과하고 c 만 error 다. 메시지가 가리키는 대상이 안쪽 함수 (String) -> Bool 이다.
1
2
3
4
5
6
7
UnappliedResult.swift:11:58: error: converting non-Sendable function value to '@Sendable (String) -> Bool' may introduce data races
9 | let a: @Sendable (A) -> (String) -> Bool = A.foo
10 | let b: @Sendable (B) -> @Sendable (String) -> Bool = B.foo
11 | let c: @Sendable (A) -> @Sendable (String) -> Bool = A.foo
| `- error: converting non-Sendable function value to '@Sendable (String) -> Bool' may introduce data races
12 | _ = (a, b, c)
13 | }
Swift 5 모드에서는 9 줄과 10 줄에도 warning 이 나오고, flag 를 켜면 11 줄 하나만 남는다.
a 는 바깥 함수가 @Sendable 이고 안쪽은 아니다. 안쪽 결과에 @Sendable 을 요구한 b 는 B 가 Sendable 이라 통과하고, 같은 요구를 한 c 는 A 가 non-Sendable 이라 막힌다. 바깥 층은 타입과 상관없이 Sendable 이고, 안쪽 층은 타입이 정한다는 뜻이다.
규칙 1 과 2 는 static 메서드에도 같이 적용된다. 제안서가 “partially applied 와 unapplied static 메서드를 포함한다” 고 쓴 부분이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Util {
static func compute(_ x: Int) -> Int { x * 2 }
}
final class Holder {
static func make() -> Int { 1 }
}
func runSendable(_ f: @escaping @Sendable (Int) -> Int) {}
func runSendable0(_ f: @escaping @Sendable () -> Int) {}
func call() {
runSendable(Util.compute)
runSendable0(Holder.make)
}
static 메서드는 인스턴스가 없으니 붙잡을 self 도 없다. Swift 5 와 Swift 5 complete 는 13 줄과 14 줄이 모두 warning 이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
StaticMethod.swift:13:20: warning: converting non-Sendable function value to '@Sendable (Int) -> Int' may introduce data races
11 |
12 | func call() {
13 | runSendable(Util.compute)
| `- warning: converting non-Sendable function value to '@Sendable (Int) -> Int' may introduce data races
14 | runSendable0(Holder.make)
15 | }
StaticMethod.swift:14:23: warning: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
12 | func call() {
13 | runSendable(Util.compute)
14 | runSendable0(Holder.make)
| `- warning: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
15 | }
16 |
Holder 는 non-Sendable class 인데도 static 메서드인 Holder.make 는 통과한다. Swift 5 + flag 와 Swift 6 에서는 진단이 0개다.
mutating 메서드 참조는 이 규칙에 들어가지 않는다. 제안서가 “unapplied 참조는 mutating 메서드에 허용되지 않는다” 고 하는데, 6.4 는 이렇게 막는다.
1
2
3
4
5
6
7
8
9
struct Counter: Sendable {
var n = 0
mutating func bump() { n += 1 }
}
func call() {
let f = Counter.bump
_ = f
}
1
2
3
4
5
6
7
Mutating.swift:7:19: error: cannot reference 'mutating' method as function value
5 |
6 | func call() {
7 | let f = Counter.bump
| `- error: cannot reference 'mutating' method as function value
8 | _ = f
9 | }
네 모드 모두 같은 error 다. Sendable 과 상관없이 언어가 원래 막는다.
key path 리터럴의 Sendable 추론
규칙 3 은 key path 리터럴이 무엇을 붙잡는지 보고 타입을 고른다. 붙잡는 것이 없거나 모두 Sendable 이면 & Sendable, subscript 인자가 non-Sendable 이거나 actor 에 묶인 속성을 가리키면 & Sendable 이 없는 key path 다.
추론된 타입을 눈으로 보려면 타입을 드러내는 기법이 필요하다. 값을 Int 에 일부러 대입하면 컴파일러가 “이 타입을 Int 로 바꿀 수 없다” 는 error 를 내면서 그 값의 추론된 타입을 메시지에 적어 준다. 아래 코드가 이 기법으로 세 가지 key path 의 타입을 본 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct User {
var name = ""
@MainActor var age: Int { 0 }
subscript(info: NonSendable) -> Entry { Entry() }
}
func inferred() {
let name = \User.name
let check1: Int = name
let age = \User.age
let check2: Int = age
let info = \User.[NonSendable()]
let check3: Int = info
}
\User.name 의 타입을 보는 줄(9 줄)의 결과다. Swift 5 와 Swift 5 complete 에서는 이렇다.
1
2
3
4
5
6
7
KeyPathInfer.swift:9:21: error: cannot convert value of type 'WritableKeyPath<User, String>' to specified type 'Int'
7 | func inferred() {
8 | let name = \User.name
9 | let check1: Int = name
| `- error: cannot convert value of type 'WritableKeyPath<User, String>' to specified type 'Int'
10 | let age = \User.age
11 | let check2: Int = age
flag 를 켠 Swift 5 와 Swift 6 에서는 이렇게 바뀐다.
1
2
3
4
5
6
7
KeyPathInfer.swift:9:21: error: cannot convert value of type 'any WritableKeyPath<User, String> & Sendable' to specified type 'Int'
7 | func inferred() {
8 | let name = \User.name
9 | let check1: Int = name
| `- error: cannot convert value of type 'any WritableKeyPath<User, String> & Sendable' to specified type 'Int'
10 | let age = \User.age
11 | let check2: Int = age
any WritableKeyPath<User, String> & Sendable 이 WritableKeyPath<User, String> & Sendable 의 6.4 표기다. name 은 var 라서 KeyPath 가 아니라 WritableKeyPath 가 되고, 붙잡는 것이 없으니 & Sendable 이 붙는다.
나머지 두 줄은 모든 모드에서 같은 타입이 나온다.
1
2
KeyPathInfer.swift:11:21: error: cannot convert value of type 'KeyPath<User, Int>' to specified type 'Int'
KeyPathInfer.swift:13:21: error: cannot convert value of type 'KeyPath<User, Entry>' to specified type 'Int'
\User.age 는 @MainActor 에 묶인 속성이라 KeyPath<User, Int> 이고, \User.[NonSendable()] 은 non-Sendable 을 subscript 인자로 붙잡아서 KeyPath<User, Entry> 다. 둘 다 & Sendable 이 붙지 않는다.
age 줄에는 이 확인과 별개의 진단이 하나 더 있다. nonisolated 함수에서 main actor 속성의 key path 를 만드는 것을 6.4 가 막는다. Swift 5 계열은 warning 이고 Swift 6 은 error 다.
1
2
3
4
5
6
7
KeyPathInfer.swift:10:19: warning: cannot form key path to main actor-isolated property 'age'; this is an error in the Swift 6 language mode
8 | let name = \User.name
9 | let check1: Int = name
10 | let age = \User.age
| `- warning: cannot form key path to main actor-isolated property 'age'; this is an error in the Swift 6 language mode
11 | let check2: Int = age
12 | let info = \User.[NonSendable()]
1
KeyPathInfer.swift:10:19: error: cannot form key path to main actor-isolated property 'age'
Swift 5 complete 에서만 하나 더 나온다. 12 줄의 subscript 인자 NonSendable() 을 붙잡는 것에 대한 warning 이고, flag 를 켜면 사라진다. 리터럴이 non-Sendable 을 붙잡는 것 자체가 이제 문제가 아니라, 그 key path 가 & Sendable 인 자리에서만 문제라는 뜻이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
KeyPathInfer.swift:12:20: warning: cannot form key path that captures non-Sendable type 'NonSendable'; this is an error in the Swift 6 language mode
10 | let age = \User.age
11 | let check2: Int = age
12 | let info = \User.[NonSendable()]
| `- warning: cannot form key path that captures non-Sendable type 'NonSendable'; this is an error in the Swift 6 language mode
13 | let check3: Int = info
14 | }
Common.swift:1:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
1 | final class NonSendable: Hashable {
| `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 | static func == (a: NonSendable, b: NonSendable) -> Bool { a === b }
3 | func hash(into hasher: inout Hasher) {}
세 모드의 결과를 한 표로 모으면 이렇다.
| 리터럴 | Swift 5, Swift 5 complete | Swift 5 + flag, Swift 6 |
|---|---|---|
\User.name | WritableKeyPath<User, String> | any WritableKeyPath<User, String> & Sendable |
\User.age | KeyPath<User, Int> | KeyPath<User, Int> |
\User.[NonSendable()] | KeyPath<User, Entry> | KeyPath<User, Entry> |
@MainActor 함수 안에서는 \User.age 가 만들어지기는 한다. 타입은 여전히 KeyPath<User, Int> 이고 & Sendable 을 직접 요구하면 막힌다.
1
2
3
4
5
6
7
8
9
10
11
struct User {
var name = ""
@MainActor var age: Int { 0 }
}
@MainActor func onMain() {
let age = \User.age
let check: Int = age
let sendableAge: KeyPath<User, Int> & Sendable = \User.age
_ = sendableAge
}
Swift 6 에서는 8 줄의 타입 확인 error 와 9 줄의 error 가 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
KeyPathActor.swift:9:52: error: type 'KeyPath<User, Int>' does not conform to the 'Sendable' protocol
7 | let age = \User.age
8 | let check: Int = age
9 | let sendableAge: KeyPath<User, Int> & Sendable = \User.age
| `- error: type 'KeyPath<User, Int>' does not conform to the 'Sendable' protocol
10 | _ = sendableAge
11 | }
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
Swift 5 complete 와 Swift 5 + flag 에서는 같은 줄이 warning 이다. 제안서도 “명시적 Sendable 표시가 sendability 검사를 대신하지는 않는다” 고 적는다. & Sendable 이라고 적는다고 해서 실제로 Sendable 이 되지는 않는다.
붙잡는 것 때문에 막히는 경우도 직접 본다. 같은 리터럴 \.[NonSendable()] 을 & Sendable 이 없는 타입과 있는 타입에 각각 대입한 코드다.
1
2
3
4
5
6
7
8
9
10
public struct User {
var name = ""
subscript(info: NonSendable) -> Entry { Entry() }
}
func makeKeyPaths() {
let entry: KeyPath<User, Entry> = \.[NonSendable()]
let sendableEntry: KeyPath<User, Entry> & Sendable = \.[NonSendable()]
_ = (entry, sendableEntry)
}
Swift 5 는 진단이 0개이고, Swift 5 complete 는 7 줄과 8 줄에 capture warning 이, 8 줄에 KeyPath 가 Sendable 이 아니라는 warning 이 나온다. flag 를 켜면 8 줄의 & Sendable 에 대한 warning 하나만 남는다. 7 줄의 \.[NonSendable()] capture warning 은 flag 가 없앤다. 앞에서 본 key path 문제, 곧 non-Sendable 을 붙잡는 리터럴에 warning 이 나던 문제가 풀린 자리다. Swift 6 에서는 8 줄만 error 이고 7 줄은 통과한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
KeyPathCapture.swift:8:56: error: type 'KeyPath<User, Entry>' does not conform to the 'Sendable' protocol
6 | func makeKeyPaths() {
7 | let entry: KeyPath<User, Entry> = \.[NonSendable()]
8 | let sendableEntry: KeyPath<User, Entry> & Sendable = \.[NonSendable()]
| `- error: type 'KeyPath<User, Entry>' does not conform to the 'Sendable' protocol
9 | _ = (entry, sendableEntry)
10 | }
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
Swift 5 complete 의 7 줄과 8 줄의 capture warning 두 개(7:39, 8:58)의 원문은 다음과 같다. 위 KeyPathInfer 의 12:20 과 같은 모양이다.
1
2
KeyPathCapture.swift:7:39: warning: cannot form key path that captures non-Sendable type 'NonSendable'; this is an error in the Swift 6 language mode
KeyPathCapture.swift:8:58: warning: cannot form key path that captures non-Sendable type 'NonSendable'; this is an error in the Swift 6 language mode
정리하면, 이제 리터럴이 non-Sendable 을 붙잡는 것은 7 줄처럼 그 key path 를 isolation 경계 너머로 보내지 않는 한 문제가 아니다. 보내려는 순간 8 줄처럼 타입이 막는다. 제안서 Motivation 이 말한 “경계를 실제로 넘을 때만 진단하라” 는 것이 이 부분이다.
key path 를 함수로 쓸 때
key path 는 함수 자리에 쓸 수 있다. \.name 을 (User) -> String 을 받는 곳에 넘기면 컴파일러가 { $0[keyPath: \.name] } 로 감싼 closure 로 바꿔 준다(SE-0249). 이 변환에서 key path 는 closure 안에 붙잡히는 것이 아니라 closure 가 그것을 한 번 감싸는 것이다. 제안서는 이 점에서 “변환에는 key path 자체가 Sendable 일 필요가 없다” 고 말한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
struct User {
var name = ""
subscript(info: NonSendable) -> Entry { Entry() }
}
func assign() {
let name: KeyPath<User, String> = \.name
let otherName: KeyPath<User, String> & Sendable = name
let fn: @Sendable (User) -> String = \.name
let value = NonSendable()
let fn2: @Sendable (User) -> Entry = \.[value]
_ = (otherName, fn, fn2)
}
Swift 6 에서는 세 줄이 서로 다른 결과를 낸다. 8 줄은 non-Sendable 로 선언한 key path 를 & Sendable 에 대입해서 막힌다. 9 줄의 @Sendable (User) -> String = \.name 은 통과한다. 11 줄은 non-Sendable 인 value 를 subscript 인자로 붙잡은 key path 라서 감싼 closure 가 value 를 붙잡게 되고, 그 closure 가 Sendable 이 아니라 막힌다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
KeyPathAssign.swift:8:53: error: type 'KeyPath<User, String>' does not conform to the 'Sendable' protocol
6 | func assign() {
7 | let name: KeyPath<User, String> = \.name
8 | let otherName: KeyPath<User, String> & Sendable = name
| `- error: type 'KeyPath<User, String>' does not conform to the 'Sendable' protocol
9 | let fn: @Sendable (User) -> String = \.name
10 | let value = NonSendable()
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
KeyPathAssign.swift:11:40: error: converting non-Sendable function value to '@Sendable (User) -> Entry' may introduce data races
9 | let fn: @Sendable (User) -> String = \.name
10 | let value = NonSendable()
11 | let fn2: @Sendable (User) -> Entry = \.[value]
| `- error: converting non-Sendable function value to '@Sendable (User) -> Entry' may introduce data races
12 | _ = (otherName, fn, fn2)
13 | }
Swift 5 complete 에서 11 줄은 11:42: warning: cannot form key path that captures non-Sendable type 이 나오고, flag 를 켜면 11:40 의 “converting non-Sendable function value” warning 으로 바뀐다. 9 줄은 모든 모드에서 통과한다.
key path 를 함수로 바꾸는 변환은 리터럴에서만 일어난다. 이미 변수에 담긴 key path 를 함수 자리에 넘기는 것은 되지 않는다. filter(name) 의 6.4 결과는 아래 KeyPathParam 에서 본다. 리터럴로 쓰면 어느 모드에서든 진단이 0개다.
1
2
3
4
5
6
7
8
9
10
struct User {
var name = ""
}
func filter<T: Sendable>(_: @Sendable (User) -> T) {}
func call() {
filter(\.name)
filter(\User.name)
}
parameter 에서 옮겨 가는 Sendable
리터럴은 context 에서 Sendable 요구를 물려받는다. parameter 가 & Sendable 을 요구하면 그 자리에 쓴 리터럴이 & Sendable 로 추론되고, 붙잡는 것이 있으면 그 자리에서 error 가 난다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct User {
var name = ""
subscript(info: NonSendable) -> Entry { Entry() }
}
func getValue<T: Sendable>(_: KeyPath<User, T> & Sendable) -> T? { nil }
func filter<T: Sendable>(_: @Sendable (User) -> T) {}
func call() {
let name = \User.name
_ = getValue(name)
_ = getValue(\.name)
_ = getValue(\.[NonSendable()])
filter(name)
}
Swift 6 에서 11 줄 getValue(name) 과 12 줄 getValue(\.name) 은 통과한다. 변수 name 은 앞에서 본 대로 & Sendable 로 추론된 값이라 parameter 와 맞고, \.name 은 parameter 가 요구한 & Sendable 이 리터럴로 옮겨 간다. 13 줄은 리터럴이 non-Sendable 을 붙잡아서 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
KeyPathParam.swift:13:16: error: type 'KeyPath<User, Entry>' does not conform to the 'Sendable' protocol
11 | _ = getValue(name)
12 | _ = getValue(\.name)
13 | _ = getValue(\.[NonSendable()])
| `- error: type 'KeyPath<User, Entry>' does not conform to the 'Sendable' protocol
14 | filter(name)
15 | }
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
14 줄 filter(name) 은 변수에 담긴 key path 를 @Sendable (User) -> T 자리에 넘기면 error 두 개가 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
KeyPathParam.swift:14:10: error: cannot convert value of type 'any WritableKeyPath<User, String> & Sendable' to expected argument type '@Sendable (User) -> T'
12 | _ = getValue(\.name)
13 | _ = getValue(\.[NonSendable()])
14 | filter(name)
| `- error: cannot convert value of type 'any WritableKeyPath<User, String> & Sendable' to expected argument type '@Sendable (User) -> T'
15 | }
16 |
KeyPathParam.swift:14:3: error: generic parameter 'T' could not be inferred
5 |
6 | func getValue<T: Sendable>(_: KeyPath<User, T> & Sendable) -> T? { nil }
7 | func filter<T: Sendable>(_: @Sendable (User) -> T) {}
| `- note: in call to function 'filter'
8 |
9 | func call() {
:
12 | _ = getValue(\.name)
13 | _ = getValue(\.[NonSendable()])
14 | filter(name)
| `- error: generic parameter 'T' could not be inferred
15 | }
이 두 error 는 Swift 5 에서도 나온다. Swift 5 모드의 14:10 메시지는 WritableKeyPath<User, String> 으로 적히는 것만 다르다. 변수에 담긴 key path 는 이미 key path 타입이라서, 함수 자리에 쓰려면 앞 절처럼 리터럴로 쓰거나 { $0[keyPath: name] } 로 직접 감싸야 한다.
Swift 5 complete 에서는 11, 12, 13 줄에 & Sendable warning 이 나오고 13:18 에 capture warning 이 더해진다. 11:16, 12:16, 13:16 이 그 자리다.
key path 합치기
KeyPath 의 appending(path:) 는 두 key path 를 이어 붙인다. \User.name 에 \String.utf8.count 를 붙이면 User 에서 이름의 길이로 가는 key path 가 된다.
제안서는 이 메서드에 & Sendable overload 를 더하자고 한다. “base 와 인자가 모두 Sendable 이면 결과도 Sendable” 인 overload 를 Sendable 의 extension 에 둔다는 제안이다. 예제는 이렇다.
1
2
3
func makeUTF8CountKeyPath<Root>(from base: KeyPath<Root, String> & Sendable) -> KeyPath<Root, Int> & Sendable {
return base.appending(path: \.utf8.count)
}
appending으로 key path 잇기
appending(path:) 는 key path 에 key path 를 이어 붙여 새 key path 를 만드는 메서드다. 오른쪽에 붙는 key path 의 Root 가 왼쪽 key path 의 Value 와 같아야 한다. 선언이 아홉 개인 것은 읽기 전용, 쓰기 가능, 참조 쓰기 가능의 조합마다 결과 타입이 달라서다. 읽기 전용 key path 에 쓰기 가능한 key path 를 붙여도 결과는 읽기 전용이다. 위 선언 중 14194 줄이 KeyPath 끼리 붙이는 것이고, 반환 타입이 KeyPath<Root, AppendedValue> 하나뿐이다.
6.4 에서 Swift 5 는 진단이 0개이고, Swift 5 complete 와 Swift 5 + flag 는 warning 이다. Swift 6 에서는 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
Appending.swift:2:15: error: type 'KeyPath<Root, Int>' does not conform to the 'Sendable' protocol
1 | func makeUTF8CountKeyPath<Root>(from base: KeyPath<Root, String> & Sendable) -> KeyPath<Root, Int> & Sendable {
2 | return base.appending(path: \.utf8.count)
| `- error: type 'KeyPath<Root, Int>' does not conform to the 'Sendable' protocol
3 | }
4 |
Swift.KeyPath:1:14: note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
1 | public class KeyPath<Root, Value> : PartialKeyPath<Root> {
| `- note: generic class 'KeyPath' does not conform to the 'Sendable' protocol
2 | @objc deinit
3 | }
appending(path:) 의 결과가 Sendable 이 아니라는 뜻이다. Xcode 27 SDK 의 표준 라이브러리 선언을 읽어서 확인했다.
1
grep -n 'func appending' "$(xcrun --show-sdk-path --sdk macosx)/usr/lib/swift/Swift.swiftmodule/arm64e-apple-macos.swiftinterface"
그 결과의 일부다.
1
2
3
4
14178: @inlinable public func appending(path: Swift::AnyKeyPath) -> Swift::AnyKeyPath? {
14194: @inlinable public func appending<Root, Value, AppendedValue>(path: Swift::KeyPath<Value, AppendedValue>) -> Swift::KeyPath<Root, AppendedValue> where Self : Swift::KeyPath<Root, Value> {
14202: @inlinable public func appending<Root, Value, AppendedValue>(path: Swift::WritableKeyPath<Value, AppendedValue>) -> Swift::WritableKeyPath<Root, AppendedValue> where Self == Swift::WritableKeyPath<Root, Value> {
14210: @inlinable public func appending<Root, Value, AppendedValue>(path: Swift::WritableKeyPath<Value, AppendedValue>) -> Swift::ReferenceWritableKeyPath<Root, AppendedValue> where Self == Swift::ReferenceWritableKeyPath<Root, Value> {
14178 줄부터 14210 줄까지 appending 선언 아홉 개가 있고 어느 것에도 Sendable 이 없다. base 의 Sendable 을 결과로 옮기는 & Sendable overload 는 이 SDK 에 들어 있지 않다.
이 점은 포럼에서도 오갔다. 리뷰에서 Jumhyn 이 이 절이 “could”, “would” 로 쓰여 가정처럼 읽힌다고 물었고(#2), beccadax 는 범위 안이라고 답하면서 toolchain 에 들어 있는지는 모르겠다고 했다(#3). xedin 은 이 변경이 toolchain 에 없고 표준 라이브러리 담당의 의견이 더 필요하다며 Joe_Groff 를 불렀다(#4). 수락 글에서 steering group 은 appending(path:) overload 세부에 대해 제안서가 조금 모호하다고 지적하면서, back deployment 같은 열린 질문은 evolution 리뷰의 범위 밖이라고 했다(수락 #1).
우회로는 key path 를 이어 붙이지 않고 처음부터 한 리터럴로 쓰는 것이다. 이 리터럴은 붙잡는 것이 없으니 & Sendable 이 된다. 이미 만들어진 Sendable key path 에 뒤를 이어야 한다면 key path 를 감싸는 함수를 쓴다.
1
2
3
4
5
6
7
8
9
10
11
struct User {
var name = ""
}
func nameLengthKeyPath() -> KeyPath<User, Int> & Sendable {
\User.name.utf8.count
}
func makeUTF8Count<Root>(from base: KeyPath<Root, String> & Sendable) -> @Sendable (Root) -> Int {
{ $0[keyPath: base].utf8.count }
}
Swift 5 는 진단이 0개, Swift 5 complete 는 nameLengthKeyPath 의 key path 에 6:3 warning 이 나오고, Swift 5 + flag 와 Swift 6 은 0개다. makeUTF8Count 는 closure 가 base 를 붙잡는데 base 가 & Sendable 이라서 반환 타입의 @Sendable 을 만족한다.
전역 함수와 local 함수
규칙 4 는 non-local 함수만 다룬다. 이유는 제안서가 “전역 함수는 아무 변수도 붙잡지 않기 때문” 이라고 설명한다. 전역 변수는 함수가 소유하지 않고 이름으로 참조할 뿐이라서 capture 가 아니라는 것이다. pitch 에서 가장 많은 이야기가 오간 자리이기도 하다.
ktoso 는 func errno() { touches horrible global state } 같은 함수를 어떻게 “Sendable 이 아니다” 로 적느냐고 물었고(#7, “Do we need @~Sendable…?”), FranzBusch 는 전역 변수를 건드리는 함수가 Sendable 로 추론되면 thread-safe 하지 않은 함수가 안전하게 보이는 구멍이 생긴다고 반대했다(#8). kavon 의 답은 이렇다(#14). SE-0302 의 정의에서 전역 변수 참조는 capture 가 아니고, 로컬 변수를 참조하는 것만 capture 다. 로컬 변수는 closure 가 살아 있는 동안 사라질 수 있기 때문이다. 그래서 이 규칙은 새 구멍을 여는 것이 아니고 “기존 규칙이 이미 그렇게 정한 것을 인정하는 것” 이라는 이야기였다. ktoso 도 이에 동의했다(#15). hborla 는 전역 상태의 data race 는 Swift 6 에서 금지되어야 한다며 곧 나올 전역 변수 제안서를 언급했다(#10). 그 제안서가 SE-0412 이다.
local 함수는 이 규칙에서 빠진다. 바깥의 로컬 값을 붙잡을 수 있기 때문이다. 아무것도 붙잡지 않는 localPure 와 ns 를 붙잡는 localUsesNS 를 둘 다 @Sendable 자리에 넘겼다.
1
2
3
4
5
6
7
8
9
func outer() {
let ns = NonSendable()
func localUsesNS() -> Int { _ = ns; return 1 }
func localPure() -> Int { 2 }
runSendable(localPure)
runSendable(localUsesNS)
}
func runSendable(_ f: @escaping @Sendable () -> Int) {}
Swift 5, Swift 5 complete, Swift 5 + flag 에서는 5 줄과 6 줄이 모두 warning 이고 Swift 6 에서는 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
LocalFunc.swift:5:15: error: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
3 | func localUsesNS() -> Int { _ = ns; return 1 }
4 | func localPure() -> Int { 2 }
5 | runSendable(localPure)
| `- error: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
6 | runSendable(localUsesNS)
7 | }
LocalFunc.swift:6:15: error: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
4 | func localPure() -> Int { 2 }
5 | runSendable(localPure)
6 | runSendable(localUsesNS)
| `- error: converting non-Sendable function value to '@Sendable () -> Int' may introduce data races
7 | }
8 |
localPure 는 아무것도 붙잡지 않는데도 막힌다. 이 규칙은 “붙잡는 것이 없음” 을 함수마다 분석해서 알아보는 규칙이 아니고, 전역 함수와 static 메서드라는 종류에만 적용된다는 뜻이다. local 함수는 @Sendable 을 직접 붙여야 하고, 그러면 그 함수 몸통이 검사받는다.
pitch 에서 FranzBusch 는 @Sendable 을 붙인 함수가 “검사가 안 되는 비상구” 라고 했다(#17). 안쪽 local 함수에 붙이면 몸통 검사가 전혀 일어나지 않는다는 걱정이다. 6.4 에서 @Sendable local 함수의 capture 는 closure 처럼 검사된다.
1
2
3
4
5
6
7
8
9
func foo() {
let ns = NonSendable()
var counter = 0
@Sendable func bar() {
_ = ns
counter += 1
}
bar()
}
Swift 6 에서 두 줄 모두 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
LocalSendable.swift:5:9: error: capture of 'ns' with non-Sendable type 'NonSendable' in a '@Sendable' local function [#SendableClosureCaptures]
3 | var counter = 0
4 | @Sendable func bar() {
5 | _ = ns
| `- error: capture of 'ns' with non-Sendable type 'NonSendable' in a '@Sendable' local function [#SendableClosureCaptures]
6 | counter += 1
7 | }
Common.swift:1:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
1 | final class NonSendable: Hashable {
| `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 | static func == (a: NonSendable, b: NonSendable) -> Bool { a === b }
3 | func hash(into hasher: inout Hasher) {}
LocalSendable.swift:6:5: error: mutation of captured var 'counter' in concurrently-executing code [#SendableClosureCaptures]
4 | @Sendable func bar() {
5 | _ = ns
6 | counter += 1
| `- error: mutation of captured var 'counter' in concurrently-executing code [#SendableClosureCaptures]
7 | }
8 | bar()
[#SendableClosureCaptures]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures>
Swift 5 모드에서는 6 줄만 warning 이고, Swift 5 complete 와 Swift 5 + flag 는 두 줄 모두 warning 이다.
non-Sendable 타입 메서드의 @Sendable 금지
규칙 5 는 non-Sendable 타입의 메서드에 @Sendable 을 붙이는 것을 막는다. 메서드는 self 를 붙잡는데, self 가 Sendable 이 아니면 @Sendable 이라는 말이 거짓이기 때문이다.
제안서 예제는 이렇다. C 는 내용을 바꾸는 class 라서 Sendable 이 아니고, generateN 은 @Sendable 이다. 동기 메서드도 하나 더 두었다.
1
2
3
4
5
6
7
8
9
10
class C {
var random: Int = 0
@Sendable func generateN() async -> Int {
random = Int.random(in: 1..<100)
return random
}
@Sendable func syncMethod() -> Int { random }
}
제안서가 보이는 위험은 이렇다. 같은 C 인스턴스를 Task.detached 안에서 쓰면서 바깥에서도 쓰면, 두 곳이 random 을 동시에 건드려 data race 가 난다. @Sendable 은 “이 메서드는 어느 task 에서 불러도 안전하다” 는 약속인데, 그 약속의 근거가 되어야 할 self 가 약속을 지킬 수 없는 타입이다. 컴파일러가 이 약속을 그냥 믿으면 검사 없이 data race 가 통과한다.
Swift 5 는 진단이 0개다. Swift 5 complete 와 Swift 5 + flag 에서는 두 메서드 모두 warning 이다.
1
2
3
4
5
6
7
8
9
SendableMethod.swift:4:3: warning: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'; this is an error in the Swift 6 language mode
1 | class C {
| `- note: class 'C' does not conform to the 'Sendable' protocol
2 | var random: Int = 0
3 |
4 | @Sendable func generateN() async -> Int {
| `- warning: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'; this is an error in the Swift 6 language mode
5 | random = Int.random(in: 1..<100)
6 | return random
Swift 6 에서는 error 이고, async 메서드와 동기 메서드 둘 다 걸린다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
SendableMethod.swift:4:3: error: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'
1 | class C {
| `- note: class 'C' does not conform to the 'Sendable' protocol
2 | var random: Int = 0
3 |
4 | @Sendable func generateN() async -> Int {
| `- error: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'
5 | random = Int.random(in: 1..<100)
6 | return random
SendableMethod.swift:9:3: error: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'
1 | class C {
| `- note: class 'C' does not conform to the 'Sendable' protocol
2 | var random: Int = 0
3 |
:
7 | }
8 |
9 | @Sendable func syncMethod() -> Int { random }
| `- error: instance method of non-Sendable type 'C' cannot be marked as '@Sendable'
10 | }
11 |
동기와 async 가 둘 다 걸리는 데에는 사연이 있다. 수락 스레드에서 KeithBauerANZ 가 관련 버그를 발견했고(#4, swift#70829), beccadax 는 그 버그가 이 제안서의 5 번 규칙이 집행되지 않는 것이라고 짚었다(#5). angela-laar 는 규칙이 non-async 메서드에만 걸리는 것 같다고 답했고(#6), Pull Request #69220 에서 async 와 non-async 둘 다 처리되어야 한다고 했다(#7). 6.4 에서는 두 메서드 모두 걸린다.
pitch 에서 dmt 는 예제를 task 안에서 C 를 만드는 모양으로 다시 쓰고, 그러면 data race 가 없지 않느냐고 물었다(#6). 인스턴스를 task 안에서만 만들어 쓰면 아무 곳으로도 새지 않기 때문이다. 규칙 5 는 그런 증명을 언어가 하지 않고, @Sendable 약속 자체를 non-Sendable 타입에서 막는 쪽이다.
기대 효과
- 메서드 참조를
@Sendable자리에 넘길 때{ @Sendable in S.f($0) }로 감싸던 코드가 필요 없어진다.g(S.f)처럼 이름만 쓰면 된다. 6.4 에서 flag 를 켠 Swift 5 모드와 Swift 6 모드가 이 줄을 0개 진단으로 통과시킨다. - 전역 함수와 static 메서드를
@Sendable자리에 그냥 넘길 수 있다.runSendable(doWork)가 warning 없이 컴파일된다. - key path 를 다른 task 로 넘기기가 쉬워진다.
\.name이& Sendable로 추론되고, parameter 가& Sendable을 요구하면 리터럴이 그것을 물려받는다. - 반대로 non-Sendable 을 붙잡는 key path 리터럴이 isolation 경계를 넘지 않는 자리에서 더는 경고를 내지 않는다. 불필요하게 컸던 SE-0302 의 제한이 풀린다.
- 검사가 안 되던
@Sendable비상구가 막힌다. non-Sendable class 의 메서드에 붙은@Sendable은 Swift 6 에서 error 이고, 직접 적은@Sendablelocal 함수의 capture 도 closure 와 같은 규칙으로 검사된다.
다른 선택지는 왜 안 됐나
제안서의 Alternatives Considered 에는 한 가지만 있고, pitch 스레드에서 나온 이야기를 보태서 네 갈래로 정리한다.
명시적 @Sendable 을 금지하지 않은 이유
규칙 3 부터 5 까지가 들어오면 함수 선언에 직접 쓰는 @Sendable 은 필요가 없어진다. 제안서는 그래서 “아예 명시적 @Sendable 을 금지하는 것” 을 대안으로 적는다. 하지만 이미 허용된 문법이어서 금지하면 source breaking 이다. Swift 6 에서 fix-it 으로 지울 수 있다 해도 방해가 되고, 붙어 있어도 해가 없으며, 옛 도구로 컴파일해야 하는 코드에서는 아직 쓸모가 있다. 그래서 이번 제안서는 금지하지 않고, 필요하면 나중에 deprecate 를 논의한다고 적는다.
pitch 에서는 반대 의견이 있었다. dnadoba 는 SE-0367 의 조건부 attribute 가 있으니 옛 컴파일러 지원은 어렵지 않다며, 적어도 warning 으로 하고 나중에 error 로 올리자고 했다(#5). FranzBusch 는 타입의 메서드에 @Sendable 을 붙이는 것은 self 가 이미 Sendable 이어야 하니 의미가 없다며 “100% 금지해야 한다” 고 했다(#8). 그 뒤에 이것이 검사 없는 비상구라는 이야기를 더했다(#17). non-Sendable 타입의 메서드에 @Sendable 을 금지하는 규칙 5 는 pitch 때부터 있었고(당시 번호는 4 번), 이 걱정과 맞닿아 있다. 전체 금지는 하지 않았다.
이 결정은 ABI 와도 이어진다. 아래 “마이그레이션” 에서 mangling 을 직접 본다.
Sendable 이 아니라고 적는 방법
이 주제는 pitch 에서 길게 이어졌지만 제안서에는 들어가지 않았다. ktoso 의 질문이 출발점이었다. 전역 함수는 감싸는 타입이 없어서 “non-Sendable 인 타입의 메서드라 추론하지 않는다” 는 길이 없으니, errno() 같은 함수가 Sendable 로 추론되지 않게 하려면 @~Sendable 같은 표기가 필요하냐는 이야기다(#7, #11). hborla 의 답은 이렇다(#10). 전역 상태에 data race 를 일으키는 접근은 Swift 6 에서 어차피 막아야 하고, 안전하지 않은 opt-out 을 도입한다면 그때 “명시적으로 @Sendable 이 아니다” 라고 적는 방법도 같이 필요해질 것이다. 지금은 그런 opt-out 이 없으니 이 제안서에 넣을 것이 아니라는 이야기였다.
dmt 는 더 근본적인 틀을 제안했다(#9, #13). 함수 타입을 “붙잡은 context 의 타입” 으로 쪼개서, context 가 Sendable 이면 함수도 Sendable 이라고 보자는 것이다. 이 틀에서는 메서드나 전역 함수나 모두 같은 규칙으로 판정하고, 타입 선언에서 상속하지 않는다. dmt 는 나아가 @NoDataRaces 같은 더 엄격한 표시가 필요하다는 이야기도 했다(#16). 제안서는 이 틀을 받아들이지 않았다. 규칙을 “메서드와 non-local 함수와 key path 리터럴” 로 한정해 가볍게 만드는 쪽을 택했다.
6.4 에서 일반 local 함수는 @Sendable 로 추론되지 않는다. 몸통의 capture 검사는 @Sendable 을 직접 붙인 local 함수(LocalSendable.swift)에만 해당한다. “이 함수는 Sendable 이 아니다” 라는 표기는 아직 언어에 없다.
getter 와 accessor
제안서의 Future Directions 는 accessor 를 이 시스템에 참여시키지 않았다고 적는다. getter 에 @Sendable 을 쓰는 것은 수요가 있으면 나중에 제안서 하나로 허용하기 쉽다는 이야기다. 이 제안서가 다루는 것은 메서드와 key path 이고 속성의 getter 를 함수 값으로 꺼내는 일은 아니다.
SE-0416 과 겹치는 부분
SE-0416 은 key path 리터럴이 함수 타입의 subtype 으로 쓰이게 하는 제안서다. 리뷰에서 KeithBauerANZ 는 이 제안서가 SE-0416 과 강하게 얽혀 있는데 어느 쪽도 그 얽힘을 쓰지 않았다고 지적했다(#6). xedin 의 답은 이렇다(#7). 얽히는 곳은 Proposed Solution 에 적힌 한 가지뿐이다. key path 와 함수 사이의 변환을 지나도 Sendable 여부가 보존된다는 점이다. 그 밖의 규칙은 SE-0416 에 영향을 받지 않는다.
앞의 KeyPathAssign.swift 의 9 줄이 그 한 가지를 보여 준다. @Sendable (User) -> String = \.name 은 key path 가 감싸져서 변환되므로 key path 자체가 Sendable 이어야 하는 것이 아니다.
마이그레이션
이 제안서는 Swift 6 언어 모드에서 기본으로 켜진다. Swift 5 모드의 프로젝트는 -enable-upcoming-feature InferSendableFromCaptures 로 먼저 켜 볼 수 있다. 수락 스레드에서 James_Dempsey 가 “6.0 으로 구현됐다고 적혀 있는데 왜 flag 가 있느냐” 고 물었고(#8), xwu 가 “Swift 6.0 은 5.10 다음의 컴파일러 릴리스이지 언어 모드가 아니다. 두 언어 모드가 6.0 에서 모두 지원되고, upcoming feature flag 가 언어 모드 사이의 조각별 이전을 해 준다” 고 답했다(#9). 컴파일러 버전과 언어 모드를 헷갈리지 않는 것이 이 제안서의 flag 를 이해하는 열쇠다.
Xcode 에서는 Swift Compiler - Upcoming Features 설정에서 켜거나 Other Swift Flags 에 -enable-upcoming-feature InferSendableFromCaptures 를 넣는다. 켠 뒤에 볼 곳은 아래와 같다.
- 타입을 적지 않은 key path 리터럴이나 함수 참조를 overload 가 있는 API 에 넘기던 곳. 제안서의 Source compatibility 절이 짚은 자리다. 아래에서 직접 측정한다.
- non-Sendable class 의 메서드에 붙은
@Sendable. Swift 6 에서 error 이니 지운다. 지우고 나서 그 메서드를 다른 task 로 넘기는 곳이 있다면 data race 가능성이 드러나는 것이니, 타입을 Sendable 로 만들거나 호출 방식을 바꾼다. - 공개 라이브러리의 명시적
@Sendable은 지우지 않는다. 아래에서 mangling 을 본다. - Sendable key path 를
appending(path:)로 합치는 곳은 앞의 우회를 쓴다.
리터럴의 타입 변화와 overload 선택
타입 표기 없는 리터럴이 & Sendable 로 추론되면, & Sendable 로 overload 된 API 에서 고르는 쪽이 달라진다. 제안서의 Source compatibility 예를 OverloadKeyPath.swift 로 만들어 실행했다.
1
2
3
4
5
6
7
8
func getValue(_: KeyPath<String, Int> & Sendable) { print("Sendable getValue") }
func getValue(_: KeyPath<String, Int>) { print("plain getValue") }
@main struct App {
static func main() {
getValue(\.utf8.count)
}
}
1
2
xcrun swiftc -parse-as-library -swift-version 5 Common.swift OverloadKeyPath.swift -o overload
./overload
Swift 5 모드는 이렇게 출력한다.
1
plain getValue
flag 를 켠 Swift 5 모드와 Swift 6 모드에서는 이렇게 출력한다.
1
Sendable getValue
같은 코드가 모드에 따라 다른 함수를 부른다. 컴파일은 모두 통과해서 진단도 나오지 않는다. 두 overload 가 같은 일을 하지 않는 API 라면 flag 를 켠 뒤 동작이 달라질 수 있는 자리다.
함수 참조를 overload 에 넘기면
함수 참조를 overload 에 넘기는 경우다. MyType 은 Sendable 이고, callback 은 @Sendable 판과 일반 판 두 개다.
1
2
3
4
5
6
7
8
9
10
11
12
struct MyType: Sendable {
func f() {}
}
func callback(_: @Sendable () -> Void) { print("Sendable callback") }
func callback(_: () -> Void) { print("plain callback") }
@main struct App {
static func main() {
callback(MyType().f)
}
}
호출 줄은 MyType().f 로 썼다. f 가 인스턴스 메서드라서 partially applied 참조를 만들려면 인스턴스가 필요하기 때문이다. 6.4 에서 Swift 5 모드는 컴파일되고 실행하면 plain callback 을 출력한다. flag 를 켠 Swift 5 모드와 Swift 6 모드는 컴파일이 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
OverloadFunc.swift:10:5: error: ambiguous use of 'callback'
3 | }
4 |
5 | func callback(_: @Sendable () -> Void) { print("Sendable callback") }
| `- note: found this candidate
6 | func callback(_: () -> Void) { print("plain callback") }
| `- note: found this candidate
7 |
8 | @main struct App {
9 | static func main() {
10 | callback(MyType().f)
| `- error: ambiguous use of 'callback'
11 | }
12 | }
Swift 5 모드에서 돌아가던 코드가 flag 를 켜면 컴파일 error 가 된다. 이 진단은 Swift 5 + flag 에서도 같다.
이 두 overload 는 @Sendable 로 타입을 적은 값을 넘겨도, { @Sendable in ... } closure 로 넘겨도 ambiguous 다. 아래 OverloadSendableValue.swift 로 확인했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct MyType: Sendable {
func f() {}
}
func callback(_: @Sendable () -> Void) { print("Sendable callback") }
func callback(_: () -> Void) { print("plain callback") }
func typedValue() {
let s: @Sendable () -> Void = MyType().f
callback(s)
}
func sendableClosure() {
callback { @Sendable in MyType().f() }
}
Swift 6 에서 두 호출이 모두 error 다.
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
OverloadSendableValue.swift:10:3: error: ambiguous use of 'callback'
3 | }
4 |
5 | func callback(_: @Sendable () -> Void) { print("Sendable callback") }
| `- note: found this candidate
6 | func callback(_: () -> Void) { print("plain callback") }
| `- note: found this candidate
7 |
8 | func typedValue() {
9 | let s: @Sendable () -> Void = MyType().f
10 | callback(s)
| `- error: ambiguous use of 'callback'
11 | }
12 |
OverloadSendableValue.swift:14:3: error: ambiguous use of 'callback'
3 | }
4 |
5 | func callback(_: @Sendable () -> Void) { print("Sendable callback") }
| `- note: found this candidate
6 | func callback(_: () -> Void) { print("plain callback") }
| `- note: found this candidate
7 |
8 | func typedValue() {
:
12 |
13 | func sendableClosure() {
14 | callback { @Sendable in MyType().f() }
| `- error: ambiguous use of 'callback'
15 | }
16 |
Swift 5 모드에서도 두 호출이 같은 error 이고, 9 줄에는 MyType().f 를 @Sendable 로 바꾸는 warning 이 하나 더 붙는다. 고르려면 일반 판 타입의 값으로 한 번 담아서 넘기는 방법이 6.4 에서 컴파일된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
struct MyType: Sendable {
func f() {}
}
func callback(_: @Sendable () -> Void) { print("Sendable callback") }
func callback(_: () -> Void) { print("plain callback") }
@main struct App {
static func main() {
let plain: () -> Void = MyType().f
callback(plain)
}
}
Swift 6 에서 컴파일되고 plain callback 을 출력한다. 실무에서는 두 overload 를 같이 두지 않는 것이 안전하다.
명시적 @Sendable 과 mangling
제안서의 ABI 절은 “메서드에서 명시적 @Sendable 을 지우면 mangling 이 바뀐다” 고 쓴다. pitch 에서 Slava_Pestov 가 “unapplied 함수 타입은 closure 표현의 sugar 일 뿐인데 어떻게 바뀌느냐” 고 물었고(#2), hborla 는 그 문장이 메서드 선언에 직접 쓴 @Sendable 을 가리키는 것이라고 답했다(#3). resilient 라이브러리가 이미 붙인 @Sendable 은 이제 추론된다 해도 지울 수 없고, 지우려면 @_silgen_name 같은 hack 이 필요하다는 이야기다.
6.4 에서 직접 보았다. plain 과 @Sendable 을 붙인 marked 를 라이브러리로 빌드한다.
1
2
3
4
public struct Box: Sendable {
public func plain() {}
@Sendable public func marked() {}
}
1
2
xcrun swiftc -emit-library -module-name M -parse-as-library -swift-version 6 Mangle.swift -o libM.dylib
nm libM.dylib | grep -E 'plain|marked'
1
2
T _$s1M3BoxV5plainyyF
T _$s1M3BoxV6markedyyYbF
Yb 가 @Sendable 표시다. demangle 하면 이름에 @Sendable 이 드러난다.
1
xcrun swift-demangle -compact '$s1M3BoxV5plainyyF' '$s1M3BoxV6markedyyYbF'
1
2
M.Box.plain() -> ()
M.Box.marked@Sendable () -> ()
marked 의 이름에서 Yb 를 빼면 다른 심볼이 되므로, 공개 라이브러리가 이미 낸 @Sendable 은 남겨 두어야 한다. 반면 & Sendable 은 marker protocol 이라 ABI 에 영향이 없다. 제안서가 key path parameter 에 & Sendable 을 더하는 방법으로 @preconcurrency public func getValue<T, U>(_: KeyPath<T, U> & Sendable) 을 적은 이유다.
nm과 swift-demangle로 심볼 이름 읽기
nm 은 라이브러리 파일에 들어 있는 심볼 목록을 보여 주는 도구이고, T 는 코드 영역에 정의된 외부 심볼이라는 뜻이다. swift-demangle 은 $s1M3BoxV6markedyyYbF 처럼 컴파일러가 만든 이름을 사람이 읽을 수 있게 되돌려 주는 도구다. -compact 는 한 줄로 출력하라는 옵션이다.
정리
- Sendable 타입의 메서드를 unapplied 나 partially applied 로 참조한 것, 전역 함수와 static 메서드는
@Sendable로 추론된다. unapplied 참조의 바깥 층은 늘 Sendable 이고, 안쪽 결과 함수가 타입의 Sendable 여부를 따른다. 6.4 에서Account.deposit은 통과하고Account().deposit만 막혔다. - key path 리터럴은 non-Sendable 을 붙잡지 않고 actor 에 묶인 속성을 가리키지 않으면
any WritableKeyPath<User, String> & Sendable같은 타입으로 추론된다. 붙잡는 것이 있으면& Sendable이 없는 key path 이고, 그 key path 를& Sendable자리에 넘기면 막힌다. key path 를 함수로 쓰는 변환은 key path 를 붙잡지 않고 감싸서 통과한다. appending(path:)의& Sendableoverload 는 6.4 SDK 의 선언 아홉 개에 없다. Sendable key path 를 이어 붙인 결과는 Sendable 이 아니고, 리터럴을 한 번에 쓰거나 함수로 감싸는 길이 있다.- local 함수는 이 규칙에서 빠지고, 직접 적은
@Sendablelocal 함수의 capture 는 closure 처럼 검사된다. non-Sendable 타입의 메서드에 붙은@Sendable은 Swift 6 에서 error 다. 6.4 는 async 와 동기 메서드 둘 다 막는다. - 이 제안서는 타입을 적지 않은 key path 리터럴과 함수 참조의 타입을 바꾼다.
OverloadKeyPath는 flag 를 켜면 부르는 overload 가 바뀌고,OverloadFunc는 6.4 에서ambiguous use of 'callback'이 된다. - 공개 라이브러리에 이미 붙은 명시적
@Sendable은 mangling 에Yb로 남아서 지우면 심볼이 바뀐다.& Sendable은 ABI 에 영향이 없다.
관련 글
- [SE-0412] Strict concurrency for global variables
- [SE-0423] Dynamic actor isolation enforcement from non-strict-concurrency contexts
- [SE-0414] Region based Isolation
- [SE-0430] sending parameter and result values
- [SE-0337] Incremental migration to concurrency checking
- [SE-0411] Isolated default value expressions
- [SE-0401] Remove Actor Isolation Inference caused by Property Wrappers

![\User.name 은 붙잡은 값이 없어 WritableKeyPath 에 Sendable 이 붙고, \User.[NonSendable()] 은 NonSendable 을 붙잡아 Sendable 이 붙지 않는 KeyPath 가 되는 모습](https://pub-1fd8ca6711bd4f3f8b74d88a697b50f9.r2.dev/2024-09-17-SE-0418/se-0418-keypath-capture.png)