[SE-0530] Async Result Support
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0530
- 상태: Implemented (Swift 6.4)
- 저자: Konrad ‘ktoso’ Malawski, Matt Massicotte
- 리뷰 매니저: Doug Gregor
- 구현: swiftlang/swift#88465
- pitch: Pitch: Result Codable conformance and async catching init (2025-03-17 부터 04-26 까지)
- 리뷰: Review (2026-04-29 시작, 05-12 까지)
- 수락: Accepted (2026-05-14)
한 줄 요약
Result 에 init(catching:) 의 비동기판이 생겼다. await Result { try await work() } 로 비동기 작업의 성공과 실패를 Result 값 하나에 담는다. 새 초기화 함수는 nonisolated(nonsending) 이라 closure 가 호출한 쪽의 isolation 에서 그대로 돌고, ~Copyable 성공 값도 받고, 인라인으로 들어가서 옛 OS 에서도 쓸 수 있다. 이 글은 이 한 줄짜리 API 를 시그니처, typed throws, isolation, overload 선택, ~Copyable 로 나누어 컴파일하고 실행해 본 기록이다.
어떤 문제였나
Result 는 성공 값 아니면 에러 하나를 담는 enum 이다. 던지는 코드를 Result 로 바꾸는 Result.init(catching:) 이 Swift 5 때부터 있어서 Result { try syncWork() } 처럼 쓸 수 있다. 그런데 closure 안에서 await 를 쓰면 이 초기화 함수를 쓸 수 없다. 동기 closure 만 받기 때문이다.
모두가 복사해 두는 짧은 확장
제안서가 짚는 문제는 이것이 어렵지 않다는 점이다. do/catch 로 다섯 줄이면 쓸 수 있어서 코드베이스마다 같은 확장이 하나씩 들어 있다. pitch 에서는 FranzBusch 가 “나는 적어도 세 프로젝트에 정의해 두었다” 고 했고(#9, 2025-03-17), 리뷰에서는 tourultimate 가 여러 코드베이스에 비슷한 확장이 있다고(#4, 2026-04-30), clayellis 가 지난주에 필요해서 pitch 스레드의 구현을 복사해 썼다고(#3, 2026-04-30) 적었다. 리뷰 초반 의견이 거의 이 이야기였다.
손으로 만든 판은 대개 이런 모양이다. 아래는 이 글의 Handmade.swift 에서 뽑은 확장이다.
1
2
3
4
5
extension Result where Failure == any Error {
init(asyncCatching body: () async throws -> Success) async {
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
겉으로는 문제가 없어 보인다. 하지만 이 확장은 isolation 에서 한 번 걸린다. @MainActor class 안에서 non-Sendable 상태를 만지는 closure 를 넘기면 컴파일이 안 된다. 무엇이 걸리는지, 표준 라이브러리판은 왜 걸리지 않는지는 뒤의 isolation 절에서 잰다. pitch 에서 FranzBusch 가 isolation: 파라미터를 붙인 판을 보여 준 것도 이 때문이다(#9).
무엇이 바뀌나
더해지는 API 는 하나다. Result 에 init(catching:) 의 async 오버로드가 생긴다. 이 글은 이것을 시그니처, 기본 사용, typed throws, isolation, overload 선택, ~Copyable 여섯 가지로 나누어 잰다.
시그니처와 놓인 자리
Swift 6.4 SDK 의 _Concurrency 모듈 interface 에서 이 초기화 함수를 찾으면 다음이 나온다.
1
2
3
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension Swift::Result where Success : ~Copyable {
@_alwaysEmitIntoClient nonisolated(nonsending) public init(catching body: nonisolated(nonsending) () async throws(Failure) -> Success) async {
위는 interface 의 일부만 발췌한 것이다. 눈에 띄는 것이 네 가지다.
- 정의된 곳이
Swift모듈이 아니라_Concurrency모듈이다.Result자체는 표준 라이브러리Swift에 있지만, 이async초기화 함수는 동시성 모듈의 확장으로 붙는다. 사용하는 쪽에서는import를 따로 하지 않아도 보인다. @available(macOS 10.15, iOS 13.0, ...)로 async/await 이 처음 나온 OS 까지 내려간다. 이유는 아래@_alwaysEmitIntoClient다.where Success : ~Copyable이라 복사할 수 없는 성공 값도 담는다.- 초기화 함수 자신과
body가 둘 다nonisolated(nonsending)이고,body는throws(Failure)다. 에러 타입이Result의Failure와 같은 typed throws 다.
@_alwaysEmitIntoClient 와 nonisolated(nonsending) 읽기
@_alwaysEmitIntoClient 는 함수 본문을 라이브러리에 두지 않고 호출하는 앱의 바이너리 안에 복사해 넣게 하는 속성이다. 앱이 그 본문을 자기 것으로 가지니 OS 에 새 심볼이 있을 필요가 없고, 그래서 제안서가 back-deploy 된다고 말한다.
nonisolated(nonsending) 은 SE-0461 에서 들어온 모양으로, 이 async 함수가 호출한 쪽의 actor 에서 그대로 돈다는 뜻이다. 함수 앞에 붙으면 함수 본문이, closure 타입 앞에 붙으면 그 closure 가 부른 쪽 isolation 에서 돈다. 둘이 같이 붙어 있어서 초기화 함수, 그 안의 body 호출, 만들어진 Result 가 모두 같은 isolation 에 있다. 이 글의 중심이 이 부분이다.
기본 사용과 에러 타입 추론
제안서의 첫 예시는 let result = await Result { try await asyncWork() } 한 줄이다. 이것을 성공, 실패, typed throws 함수, 던지지 않는 함수, 명시적 타입까지 다섯 가지로 돌렸다.
Basic.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct Boom: Error { let n: Int }
func asyncWork(_ ok: Bool) async throws -> Int { try await Task.sleep(for: .milliseconds(5)); if ok { return 42 }; throw Boom(n: 1) }
func typedWork() async throws(Boom) -> String { throw Boom(n: 2) }
func safeWork() async -> String { "never fails" }
@main struct M {
static func main() async {
let r1 = await Result { try await asyncWork(true) }
print("r1:", r1)
let r2 = await Result { try await asyncWork(false) }
print("r2:", r2)
let r3 = await Result { try await typedWork() }
print("r3:", type(of: r3), r3)
let r4 = await Result { await safeWork() }
print("r4:", type(of: r4), r4)
let r5 = await Result<Int, any Error> { try await asyncWork(true) }
print("r5:", type(of: r5))
switch r2 {
case .success(let v): print("value", v)
case .failure(let e): print("failure", e)
}
print("get:", (try? r1.get()) ?? -1)
}
}
1
2
3
bash diag.sh Basic.swift
xcrun swiftc -parse-as-library -swift-version 6 Basic.swift -o x
./x
1
[exit 0]
1
2
3
4
5
6
7
r1: success(42)
r2: failure(Basic.Boom(n: 1))
r3: Result<String, Error> failure(Basic.Boom(n: 2))
r4: Result<String, Never> success("never fails")
r5: Result<Int, Error>
failure Boom(n: 1)
get: 42
진단은 없다.
Result 로 감싸고 get 으로 꺼내기
Result 는 .success(Success) 와 .failure(Failure) 두 case 를 가진 enum 이다. init(catching:) 은 closure 를 실행해서 값을 돌려주면 .success 로, 에러를 던지면 .failure 로 담아 주는 초기화 함수다. 이 글의 주인공은 같은 이름의 async 판 이다. get() 은 반대로 .success 면 값을 돌려주고 .failure 면 그 에러를 던진다. try? 는 던져진 에러를 nil 로 바꾸는 문법이라 (try? r1.get()) ?? -1 은 값이 없으면 -1 이 된다. Task.sleep(for:) 는 지정한 시간만큼 현재 task 를 재워서 asyncWork 가 정말 비동기로 일하는 척하게 한 것이다.
해석은 네 묶음이다. r1 과 r2 는 성공과 실패가 각각 .success(42) 와 .failure(Boom(n: 1)) 로 담겼다. r2 가 Basic.Boom(n: 1) 이라고 모듈 이름이 붙어 찍힌 것은 Result 의 description 이 payload 를 debug 표현으로 찍기 때문이다. 아래 print("failure", e) 는 Boom(n: 1) 로 이름만 나온다. 둘째로 r3 이다. 호출한 함수 typedWork 가 throws(Boom) 인데도 결과 타입은 Result<String, Boom> 이 아니라 Result<String, Error> 다. 에러 타입이 Boom 으로 보존되는 줄 알았다면 어긋난다. 이유는 다음 절에서 따로 잰다. 셋째로 r4 는 closure 가 던지지 않으면 Failure 가 Never 로 추론된다. 실패할 수 없는 Result 가 된다는 뜻이다. r5 는 Result<Int, any Error> 라고 적은 대조군으로, 추론과 같은 타입이다.
typed throws 와 만났을 때
itMaxence 가 리뷰에서 typed throws 와 같이 쓰이느냐고 물었다(#7, 2026-05-02). Result<Bool, SomeTypedError> 라고 타입을 명시해야 에러 타입이 안 사라지는지 궁금해한 것이다. 앞 절의 r3 이 이미 그 방향을 가리키고 있어서, 세 가지로 갈라 쟀다.
Typed.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Boom: Error { let n: Int }
func typedWork() async throws(Boom) -> String { throw Boom(n: 2) }
func syncTyped() throws(Boom) -> String { throw Boom(n: 3) }
@main struct M {
static func main() async {
let a = await Result { try await typedWork() }
print("inferred:", type(of: a))
let b = await Result { () async throws(Boom) -> String in try await typedWork() }
print("closure annotated:", type(of: b))
let d = Result { try syncTyped() }
print("sync inferred:", type(of: d))
}
}
1
2
3
bash diag.sh Typed.swift
xcrun swiftc -parse-as-library -swift-version 6 Typed.swift -o x
./x
1
[exit 0]
1
2
3
inferred: Result<String, Error>
closure annotated: Result<String, Boom>
sync inferred: Result<String, Error>
a 는 closure 를 그냥 적었고 Result<String, Error> 가 나왔다. b 는 closure 의 시그니처를 () async throws(Boom) -> String 으로 적었더니 Result<String, Boom> 이 나왔다. 마지막 d 가 대조군이다. 이것은 기존 동기판 Result { try syncTyped() } 인데 똑같이 Error 로 추론된다. 그러니 이 현상은 새 async 판의 결함이 아니라 closure 의 에러 타입 추론이 원래 그렇게 동작하는 것이다. closure 본문에 try 가 있으면 그 closure 가 던질 수 있는 에러는 any Error 로 추론되고, 본문 안 호출이 typed throws 여도 그 타입이 closure 의 에러 타입으로 승격되지 않는다. closure 의 throw 타입 추론은 SE-0413 typed throws 가 다루는 영역이다.
그럼 컨텍스트에서 Result<String, Boom> 이라고 타입을 적어 주면 되는가. 이것을 TypedCtx.swift 로 쟀다. async 판과 동기판을 나란히 넣었다.
TypedCtx.swift
1
2
3
4
5
6
7
8
9
10
11
12
struct Boom: Error { let n: Int }
func typedWork() async throws(Boom) -> String { throw Boom(n: 2) }
func syncTyped() throws(Boom) -> String { throw Boom(n: 3) }
func f() async {
let c = await Result<String, Boom> { try await typedWork() }
_ = c
}
func g() {
let s = Result<String, Boom> { try syncTyped() }
_ = s
}
@main struct M { static func main() async { await f(); g() } }
1
bash diag.sh TypedCtx.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TypedCtx.swift:5:38: error: invalid conversion of thrown error type 'any Error' to 'Boom'
3 | func syncTyped() throws(Boom) -> String { throw Boom(n: 3) }
4 | func f() async {
5 | let c = await Result<String, Boom> { try await typedWork() }
| `- error: invalid conversion of thrown error type 'any Error' to 'Boom'
6 | _ = c
7 | }
TypedCtx.swift:9:32: error: invalid conversion of thrown error type 'any Error' to 'Boom'
7 | }
8 | func g() {
9 | let s = Result<String, Boom> { try syncTyped() }
| `- error: invalid conversion of thrown error type 'any Error' to 'Boom'
10 | _ = s
11 | }
[exit 1]
두 줄 모두 같은 error 다. 컨텍스트가 Boom 을 요구해도 closure 는 any Error 를 던지는 closure 로 추론되어 변환이 막힌다. 5번 줄이 async 판, 9번 줄이 동기판이다. 같은 규칙이라는 대조가 이 한 번의 실행에서 나온다.
FullTypedThrows 는 upcoming feature 목록에 없고 experimental 기능이다. production 컴파일러에서 experimental 로 켜면 다음과 같이 거부된다.
1
bash diag.sh -enable-experimental-feature FullTypedThrows TypedCtx.swift
1
2
<unknown>:0: error: experimental feature 'FullTypedThrows' cannot be enabled in production compiler
[exit 1]
이 컴파일러에서는 그 기능으로 추론을 바꿔 볼 수 없다. 대신 async 와 Result 가 없는 일반 함수에서도 같은 error 가 나는지 PlainTyped.swift 로 대조했다.
PlainTyped.swift
1
2
3
4
5
6
7
8
9
10
11
struct Boom: Error { let n: Int }
func syncTyped() throws(Boom) -> String { throw Boom(n: 3) }
func typedWork() async throws(Boom) -> String { throw Boom(n: 2) }
func take(_ b: () throws(Boom) -> String) -> String { (try? b()) ?? "caught" }
func takeA(_ b: () async throws(Boom) -> String) async -> String { (try? await b()) ?? "caught" }
func gen<E: Error>(_ b: () throws(E) -> String) -> E.Type { E.self }
@main struct M { static func main() async {
print(take { try syncTyped() })
print(await takeA { try await typedWork() })
print(gen { try syncTyped() })
} }
1
bash diag.sh PlainTyped.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
PlainTyped.swift:8:14: error: invalid conversion of thrown error type 'any Error' to 'Boom'
6 | func gen<E: Error>(_ b: () throws(E) -> String) -> E.Type { E.self }
7 | @main struct M { static func main() async {
8 | print(take { try syncTyped() })
| `- error: invalid conversion of thrown error type 'any Error' to 'Boom'
9 | print(await takeA { try await typedWork() })
10 | print(gen { try syncTyped() })
PlainTyped.swift:9:21: error: invalid conversion of thrown error type 'any Error' to 'Boom'
7 | @main struct M { static func main() async {
8 | print(take { try syncTyped() })
9 | print(await takeA { try await typedWork() })
| `- error: invalid conversion of thrown error type 'any Error' to 'Boom'
10 | print(gen { try syncTyped() })
11 | } }
[exit 1]
take 는 () throws(Boom) -> String 을 받는 평범한 함수이고 takeA 는 그 async 판이다. 둘 다 Result 가 없는데도 trailing closure { try syncTyped() } 는 같은 invalid conversion of thrown error type 'any Error' to 'Boom' 으로 막힌다. 제네릭 gen 은 던지는 타입을 E 로 받는 함수라 오류가 없다. 그러니 이 규칙은 Result 와 상관없는 closure 추론의 성질이다.
결론은 이렇다. typed throws 를 보존하려면 b 처럼 closure 시그니처를 () async throws(Boom) -> String 으로 직접 적는다. 이 제안은 초기화 함수 쪽에서 body 를 throws(Failure) 로 받아 두었을 뿐이고, closure 의 에러 타입을 바꿔 주는 장치는 아니다. 추론이 any Error 로 가는 것은 closure 를 가진 모든 API 가 같다.
호출자 isolation 에서 도는 body
이 제안서에서 가장 많은 것이 들어 있는 한 줄은 nonisolated(nonsending) 이다. 동시성에서 이것이 필요한 이유는 closure 가 non-Sendable 상태를 만지는 순간 드러난다.
nonisolated(nonsending) 이란?
async 함수는 부른 쪽 actor 에서 돌 수도 있고, 부른 쪽을 떠나 전역 executor 에서 돌 수도 있다. nonisolated async 함수가 부른 쪽 actor 에서 돌게 하는 표시가 nonisolated(nonsending) 이고, 부른 쪽을 떠나 전역 executor 로 가는 쪽은 @concurrent 라고 부른다. 표시를 안 하면 어느 쪽이 되는지는 NonisolatedNonsendingByDefault 기능에 달려 있고, Swift 6 모드의 기본은 아직 @concurrent 다. 아래 Handmade.swift 가 그 기본값으로 막히는 모습이다. 비유하면 nonsending 은 부른 자리에서 일을 바로 처리하는 것이고, @concurrent 는 일을 다른 창구로 넘기는 것이다. 일을 남에게 넘기려면 넘기는 물건이 안전하게 건네지는지, 즉 Sendable 이거나 sending 으로 소유가 확실한지를 컴파일러가 따진다. 이 규칙은 SE-0461 글에서 자세히 다뤘다.
이 초기화 함수는 body 를 부르는 쪽이 어디서 오든 같은 isolation 에서 돌려야 한다. 그래서 둘 다 nonsending 이다.
nonsending 이 하는 일
@MainActor class 와 non-Sendable 상태를 가진 actor 안에서, 그 상태를 만지는 closure 를 Result { ... } 에 넘겼다.
Iso.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
final class Counter { var n = 0 } // non-Sendable
func work() async throws -> Int { 1 }
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result {
MainActor.assertIsolated("body on MainActor")
counter.n += try await work()
return counter.n
}
print("main model:", r, "isolation:", #isolation as Any)
}
}
actor Store {
var cache: [Int] = []
let counter = Counter()
func load() async {
let r = await Result {
self.assertIsolated("body on Store")
cache.append(try await work())
counter.n += 1
return cache.count
}
print("actor store:", r)
}
}
@main struct M {
static func main() async {
await Model().refresh()
await Store().load()
}
}
1
2
3
bash diag.sh Iso.swift
xcrun swiftc -parse-as-library -swift-version 6 Iso.swift -o x
./x
1
[exit 0]
1
2
main model: success(1) isolation: Swift.MainActor
actor store: success(1)
진단이 없다. 클래스 Counter 는 Sendable 이 아니고 @MainActor class Model 의 상태로 묶여 있다. closure 가 그 상태를 읽고 쓰는데 Swift 6 모드가 아무 말도 안 한다. 실행 출력도 맞다.
MainActor.assertIsolated 와 #isolation 으로 isolation 확인하기
MainActor.assertIsolated(_:file:line:) 는 지금 코드가 MainActor 에서 도는지 확인하고 아니면 프로그램을 멈추는 함수다. actor 인스턴스에도 self.assertIsolated(...) 로 같은 일을 하는 메서드가 있다. 두 줄이 모두 통과했다는 것은 body 가 Result 초기화 함수 안에서 호출되었는데도 호출자의 isolation 에서 돌았다는 뜻이다. #isolation 은 지금 코드의 isolation 을 값으로 돌려주는 매크로로, 출력 Swift.MainActor 는 print 가 찍힌 자리가 MainActor 라는 표시다. 실행 파일이 CLI 라서 Thread.isMainThread 같은 값으로는 판단하지 않았다. CLI 의 static func main() async 는 첫 suspension 뒤에 main queue 를 main thread 가 아닌 thread 에서 돌리기 때문이다.
actor Store 쪽도 같다. cache 는 actor 의 isolated 상태이고, body 안에서 자유롭게 쓴다. self.assertIsolated 가 통과했다.
이것이 nonsending 의 효과다. closure 가 호출자의 isolation 에 머물러서 counter 같은 non-Sendable 상태를 Sendable 검사 없이 만질 수 있다.
직접 만든 판이 막히는 이유
같은 코드를 nonisolated(nonsending) 없이 직접 만든 판으로 돌려 보았다. 앞의 Handmade.swift 확장을 Iso.swift 의 Model 에 붙였다.
Handmade.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final class Counter { var n = 0 }
func work() async throws -> Int { 1 }
extension Result where Failure == any Error {
init(asyncCatching body: () async throws -> Success) async {
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result(asyncCatching: {
counter.n += try await work()
return counter.n
})
print(r)
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
bash diag.sh Handmade.swift
1
2
3
4
5
6
7
8
9
10
11
12
Handmade.swift:13:19: error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
11 | let counter = Counter()
12 | func refresh() async {
13 | let r = await Result(asyncCatching: {
| |- error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated value of non-Sendable type '() async throws -> Int' to @concurrent initializer 'init(asyncCatching:)' risks causing races in between main actor-isolated and @concurrent uses
14 | counter.n += try await work()
15 | return counter.n
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
error 다. note 를 읽으면 원인이 보인다. 직접 만든 init(asyncCatching:) 에는 아무 isolation 표시가 없어서 @concurrent 로 취급되고, 그 초기화 함수에 MainActor 에 묶인 closure 를 넘기는 것이 sending 이 되어 버린다. 그 closure 는 counter 를 잡고 있는데 counter 는 MainActor 가 가진 non-Sendable 객체라, 넘어간 쪽에서 돌 때 원래 쪽과 동시에 접근할 위험이 있다. 이 진단이 SE-0414 와 SE-0430 의 region isolation 과 sending 규칙이다.
대조는 두 가지를 했다. 첫째, NonisolatedNonsendingByDefault 업커밍 기능을 켜면 같은 파일이 통과한다.
1
bash diag.sh -enable-upcoming-feature NonisolatedNonsendingByDefault Handmade.swift
1
[exit 0]
이 기능은 nonisolated async 함수의 기본을 @concurrent 에서 nonsending 으로 바꾼다. 직접 만든 판이 막힌 것은 표시가 없어서 기본값인 @concurrent 로 취급되었기 때문이라는 해석과 맞는다.
표준 라이브러리판은 nonisolated(nonsending) 이 두 군데 있다. 초기화 함수 앞과 body 타입 앞이다. 어느 쪽이 error 를 없애는지 한 곳씩만 적은 두 판으로 갈라 보았다.
OnlyInit.swift 는 초기화 함수에만 표시했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final class Counter { var n = 0 }
func work() async throws -> Int { 1 }
extension Result where Failure == any Error {
nonisolated(nonsending) init(asyncCatching body: () async throws -> Success) async {
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result(asyncCatching: {
MainActor.assertIsolated("body on MainActor")
counter.n += try await work()
return counter.n
})
print("only init:", r)
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
2
3
bash diag.sh OnlyInit.swift
xcrun swiftc -parse-as-library -swift-version 6 OnlyInit.swift -o x
./x
1
[exit 0]
1
only init: success(1)
진단이 없고 assertIsolated 도 통과한다. OnlyBody.swift 는 body 타입에만 표시했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final class Counter { var n = 0 }
func work() async throws -> Int { 1 }
extension Result where Failure == any Error {
init(asyncCatching body: nonisolated(nonsending) () async throws -> Success) async {
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result(asyncCatching: {
MainActor.assertIsolated("body on MainActor")
counter.n += try await work()
return counter.n
})
print("only body:", r)
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
bash diag.sh OnlyBody.swift
1
2
3
4
5
6
7
8
9
10
11
12
OnlyBody.swift:11:19: error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
9 | let counter = Counter()
10 | func refresh() async {
11 | let r = await Result(asyncCatching: {
| |- error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated value of non-Sendable type '() async throws -> Int' to @concurrent initializer 'init(asyncCatching:)' risks causing races in between main actor-isolated and @concurrent uses
12 | MainActor.assertIsolated("body on MainActor")
13 | counter.n += try await work()
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
Handmade.swift 와 같은 error 가 그대로 나온다. 이 측정으로 말할 수 있는 것은 error 를 없애는 쪽이 초기화 함수에 붙은 표시라는 점이다. body 쪽 표시는 이 예제에서 error 를 바꾸지 않는다.
마지막으로, pitch 에서 FranzBusch 가 SE-0461 이 수락되기 전까지 필요하다고 보여 준(#9) isolation: 파라미터 방식을 Handmade.swift 모양에 맞춰 옮긴 판이다. 원문은 typed throws 와 catching 라벨을 쓰고, 여기서는 위 확장과 같은 asyncCatching 으로 맞췄다.
Param.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
final class Counter { var n = 0 }
func work() async throws -> Int { 1 }
extension Result where Failure == any Error {
init(
isolation: isolated (any Actor)? = #isolation,
asyncCatching body: () async throws -> Success
) async {
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result(asyncCatching: {
counter.n += try await work()
return counter.n
})
print("param version:", r, "isolation:", #isolation as Any)
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
2
3
bash diag.sh Param.swift
xcrun swiftc -parse-as-library -swift-version 6 Param.swift -o x
./x
1
[exit 0]
1
param version: success(1) isolation: Swift.MainActor
이 판도 통과하고 MainActor 에서 돈다. isolated (any Actor)? = #isolation 은 호출한 쪽의 actor 를 기본값으로 받아 함수가 그 actor 에서 돌게 하는 옛 방식이다. 그러나 함수 시그니처에 isolation 파라미터가 하나 더 붙어서 공개 API 가 지저분해지고, nonsending 은 이 파라미터를 눈에 안 보이는 속성으로 바꾼 것이다.
body 의 결과와 Result 는 어느 isolation 에 묶이나
grynspan 은 리뷰에서 body 의 결과가 sending 이어야 하지 않느냐고 물었다(#5, 2026-04-30). FranzBusch 는 아니라고 답했다(#6, 2026-04-30). closure 가 nonisolated(nonsending) 이고 Result 가 Success 에 조건부로 Sendable 이라서, body 가 돌려주는 값은 현재 isolation region 에 묶인다. Result 자체도 마찬가지라 isolation 도메인을 넘길 수 없다는 것이다. 이 주장도 직접 쟀다.
Region.swift
1
2
3
4
5
6
7
8
9
10
11
12
final class Counter { var n = 0 } // non-Sendable
func make() async throws -> Counter { Counter() }
@MainActor final class Model {
func refresh() async {
let r = await Result { try await make() }
Task.detached {
print(r)
}
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
bash diag.sh Region.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
Region.swift:7:10: error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
5 | func refresh() async {
6 | let r = await Result { try await make() }
7 | Task.detached {
| `- error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
8 | print(r)
| `- note: closure captures 'r' which is accessible to main actor-isolated code
9 | }
10 | }
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
[exit 1]
Counter 는 non-Sendable 이다. Result<Counter, any Error> 도 non-Sendable 이라, Result 초기화를 거친 r 을 Task.detached 에 잡아 가면 error 가 나고 note 가 “r 은 MainActor 가 접근할 수 있다” 고 짚는다. Task.detached 는 현재 task 와 이어지지 않는 새 task 를 만들고, closure 를 sending 으로 받는다. 원인이 non-Sendable 자체인지 따져 보려고 같은 make() 를 Result 없이 직접 불러서 보내 보았다.
RegionDirect.swift
1
2
3
4
5
6
7
8
9
10
11
12
final class Counter { var n = 0 } // non-Sendable
func make() async throws -> Counter { Counter() }
@MainActor final class Model {
func refresh() async {
guard let c = try? await make() else { return }
Task.detached {
print(c)
}
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
bash diag.sh RegionDirect.swift
1
[exit 0]
진단이 없다. 같은 non-Sendable Counter 인데 직접 받은 값은 보낼 수 있고, nonisolated(nonsending) 초기화를 거친 Result 는 보낼 수 없다. 값이 MainActor 의 region 에 묶이는 것이 nonsending 초기화를 거치면서 일어난 일이다. FranzBusch 는 이것을 의도로 설명했다. 직접 호출과 달리 결과를 다른 도메인으로 보낼 수 없다는 것이 이 설계의 값이다. 다른 대조군은 Success 를 Sendable 인 Int 로 바꾼 같은 코드다.
1
bash diag.sh RegionSendable.swift
1
[exit 0]
진단이 없다. Result<Int, any Error> 는 Sendable 이니 보낼 수 있다. 조건부 Sendable 이 그대로 작동한 것이다. 그래서 body 의 결과에 sending 을 요구할 필요가 없었다. sending 이 있으면 non-Sendable 결과를 isolation 사이로 넘기는 일을 허락하려는 것인데, 이 초기화 함수의 목적은 그것이 아니다.
동기판과의 overload 선택
같은 이름 init(catching:) 의 동기판과 비동기판이 같이 있으니 어느 쪽이 골라지는지 봤다. await 를 붙인 동기 closure 와, 비동기 closure 에 await 를 뺀 경우다.
Overload.swift
1
2
3
4
5
6
7
8
func syncWork() throws -> Int { 1 }
func asyncWork() async throws -> Int { 2 }
func f() async {
let a = await Result { try syncWork() }
let b = Result { try await asyncWork() }
_ = (a, b)
}
@main struct M { static func main() async { await f() } }
1
bash diag.sh Overload.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Overload.swift:4:11: warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
2 | func asyncWork() async throws -> Int { 2 }
3 | func f() async {
4 | let a = await Result { try syncWork() }
| `- warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
5 | let b = Result { try await asyncWork() }
6 | _ = (a, b)
Overload.swift:5:11: error: expression is 'async' but is not marked with 'await'
3 | func f() async {
4 | let a = await Result { try syncWork() }
5 | let b = Result { try await asyncWork() }
| |- error: expression is 'async' but is not marked with 'await'
| `- note: call is 'async'
6 | _ = (a, b)
7 | }
[#UnnecessaryEffectMarker]: <https://docs.swift.org/compiler/documentation/diagnostics/unnecessary-effect-marker>
[exit 1]
4번 줄은 await 가 있는데 closure 가 동기라서 warning 이 난다. 컴파일러가 closure 본문을 보고 동기판을 골랐고, 그러니 이 호출에는 async 인 것이 없다는 뜻이다. 5번 줄은 반대다. closure 에 await 가 있어서 비동기판이 골라지는데 Result { ... } 앞에 await 가 없어서 error 가 나고, note 는 “호출이 async” 라고 짚는다. 요약하면 closure 본문이 동기냐 비동기냐가 판을 정하고, 앞의 await 는 그 결과를 표시하는 쪽이다. 그러니 이 API 를 쓰려면 await Result { try await ... } 처럼 두 await 가 다 있어야 한다. 바깥 하나는 초기화 함수가 async 라서, 안쪽 하나는 closure 안의 비동기 호출 때문이다.
복사할 수 없는 성공 값
where Success : ~Copyable 이라 복사할 수 없는 값을 Result 에 담을 수 있다. 값이 하나뿐인 Token 으로 돌렸다.
Back.swift
1
2
3
4
5
6
7
8
9
10
11
struct Token: ~Copyable { let id: Int }
func mint() async throws -> Token { Token(id: 9) }
@main struct M {
static func main() async {
let r = await Result { try await mint() }
switch consume r {
case .success(let t): print("token", t.id)
case .failure(let e): print(e)
}
}
}
1
2
3
bash diag.sh Back.swift
xcrun swiftc -parse-as-library -swift-version 6 Back.swift -o x
./x
1
[exit 0]
1
token 9
~Copyable 는 “복사할 수 없다” 는 제약이다. Token 은 복사되지 않고 소유권이 한 곳에만 있다. consume r 은 r 의 소유권을 switch 로 넘긴다. 이 초기화 함수의 본문은 self = .success(try await body()) 라 값을 한 번 옮길 뿐 복사하지 않아서 통과한다. 이 줄이 제안서의 where Success: ~Copyable 이 실제로 가능하다는 증거다.
스레드에서 오간 이야기
제안서는 짧아서 스레드도 짧다. pitch 는 2025-03-17 부터 04-26 까지, 리뷰는 2026-04-29 부터 05-12 까지였다. 두 스레드 사이가 1년이 넘는다. 시간순으로 짚는다.
pitch 첫날 (2025-03-17)
ktoso 는 두 가지를 제안했다(#1). Result 에 Codable conformance 를 추가하는 것, 그리고 typed throws 를 쓰는 async 오버로드 init(catching:) 이다. 이름도 Result Codable conformance and async catching init 이었다.
같은 날 반응이 둘로 갈렸다. async 초기화에는 찬성이 이어졌다. KeithBauerANZ 는 “대형 yes, 늘 필요하다” 고 했다(#2). Jon_Shier 는 Result API 가 늘어나는 것 자체를 환영한다고 했다(#3). FranzBusch 는 자기 프로젝트 세 곳에 이 메서드가 있다고 하면서 SE-0461 이 수락되기 전까지는 isolation 파라미터가 필요하다는 판을 보여 주었다(#9).
반대 쪽은 Codable 에 쏠렸다. KeithBauerANZ 는 enum 의 자동 synthesis 가 다른 어떤 관행과도 맞지 않는 JSON 을 만들어서 쓸 일이 없을 것이라고 했다(#2). 예로 {"success": {"_0": ...}} 모양을 보였다. Jon_Shier 는 이미 6년이 늦었다고 했다(#3). 새 함수는 충돌을 피할 수 있지만 새 conformance 는 기존 코드와 호환될 방법이 없고, 기본 synthesis 는 아무도 직접 쓰지 않을 모양이라는 것이다. 이어서 그는 Xcode 16.3 beta 에서 CLLocationCoordinate2D 에 Codable 이 추가되어 자기 디코딩이 깨진 일을 말하며(#8), 새 conformance 가 back-deploy 되는지 물었다. pyrtsa 는 Codable 대신 Decodable 과 Encodable 을 따로 conditional conformance 로 하자고 했고(#6), ktoso 는 좋은 지적이라고 받았다(#7). AliMark71 은 async 초기화에 “definitely a +1” 을 보내고, Codable 에는 “generally +1” 이라고 하면서도 자신은 Codable 전문가가 아니라 의견을 보류한다고 했다(#10, 2025-04-26).
리뷰에 올라온 제안서는 Async Result Support 라는 이름으로 async 초기화 하나만 담고 있고 Codable 은 없다. 이 글이 따라가는 API 는 그래서 이것 하나다.
리뷰 (2026-04-29 부터 05-12)
Doug Gregor 가 리뷰를 열었다(#1, 2026-04-29). 초반 의견은 환영이 대부분이었다. Dmitriy_Ignatyev 는 자기도 늘 복사하는 다른 helper 들(isSuccess, isFailure, value, error, mapAsVoid(), infallibleValue)도 표준 라이브러리에 넣을 만하냐고 물었다(#2, 2026-04-29). clayellis 는 이것이 표준 라이브러리에 있어야 하는 좁은 제안이라고 했고(#3), tourultimate 도 같은 확장이 여러 곳에 있다고 했다(#4).
grynspan 은 두 가지를 말했다(#5, 2026-04-30). 이 인터페이스에 확고히 찬성한다는 것, 그리고 body 의 결과가 sending 이어야 하는 것 아니냐는 의문이다. 그는 Dmitriy 가 든 helper 들이 이미 case .success, try? get(), map { _ in }, get() 으로 가능하다고 표로 정리했고, 그런 helper 를 넣으려면 큰 개선임을 보여야 한다고 했다. FranzBusch 는 sending 이 필요 없다고 답했다(#6, 같은 날). 앞 절에서 Region.swift 로 잰 것이 이 대답이다.
itMaxence 는 typed throws 와 같이 쓰이느냐고 물었다(#7, 2026-05-02). 앞 절의 Typed.swift 와 TypedCtx.swift 가 이 질문에 대한 답이 된다.
John_McCall 은 helper 이야기에 선을 그었다(#9, 2026-05-04). 그런 API 가 아직 Result 에 들어오지 않은 것은 enum 패턴 매칭의 일반적 개선이 더 나을 수 있어서이고, 이 리뷰에서는 더 논의하지 않는다고 했다. 이 API 는 그 자체로 합리적인 추가이고 제안이 좁은 것은 괜찮으니 다른 추가는 따로 pitch 하라는 말이다.
수락 (2026-05-14)
Doug Gregor 는 수락 공지(#1)에서 리뷰가 5월 12일에 끝났고 피드백이 긍정적이었으며 Language Steering Group 이 수락했다고 알렸다. 리뷰 스레드에도 같은 날 짧은 글이 올라왔다(#10).
기대 효과
- 같은 확장을 코드베이스마다 복사하던 것이 없어진다. pitch 의 FranzBusch(#9)와 리뷰의 tourultimate(#4)가 자기 프로젝트에 있다고 한 바로 그것이다
- 직접 만든 판이 isolation 에서 막히던 것(
Handmade.swift)이 표준 라이브러리판에서는 없다.nonsending덕분에@MainActorclass 나 actor 안에서 non-Sendable 상태를 만지는 closure 를 그대로 넘길 수 있다 - 던지지 않는 closure 는
Result<T, Never>로 나와서 실패할 수 없다는 사실이 타입에 남는다 ~Copyable값도 담아서 복사할 수 없는 자원을 비동기로 만든 결과도Result로 다룬다
다른 선택지는 왜 안 됐나
제안서에는 “alternatives considered” 절이 없고, 스레드에서 나온 대안이 그 자리를 채운다.
isolation:파라미터를 붙인 판: pitch 에서 FranzBusch 가 보여 준 방식(#9)이다.Handmade.swift모양에 맞춘Param.swift로 쟀듯 동작한다. 하지만 SE-0461 의nonisolated(nonsending)이 같은 일을 시그니처에 파라미터를 더하지 않고 한다body의 결과를sending으로: grynspan 의 의문이다(#5). FranzBusch 가 결과는 호출자 isolation 에 묶이는 것이 의도라고 답했고(#6),Region.swift와 대조군이 그 성질을 보여 준다Codableconformance 를 같이: pitch 에서 반대가 이어졌고(#2, #3), 리뷰 제안서에는 없다isSuccess,value,mapAsVoid()같은 helper 를 같이: Dmitriy_Ignatyev 가 제안했고(#2), grynspan 은 이미 다른 방법이 있다고 짚었으며(#5), John_McCall 은 따로 pitch 하라고 했다(#9)- 직접 만들어 쓰기: Jon_Shier 가
Codable에 대해 말했듯 지금도 할 수 있다(#3). 하지만Handmade.swift가 보여 주듯 isolation 을 맞추지 않으면 non-Sendable 상태에서 막힌다
Swift 6 모드와 마이그레이션
순수한 추가라 소스 호환은 영향이 없다고 제안서가 말한다. 두 가지를 직접 쟀다.
먼저 기존 동기 호출이 그대로인지 본다.
Compat.swift
1
2
3
4
5
6
7
8
9
10
func syncWork() throws -> Int { 1 }
func asyncWork() async throws -> Int { 2 }
func f() async {
let a = Result { try syncWork() }
let b = await Result { try await asyncWork() }
print("a:", type(of: a), a)
print("b:", type(of: b), b)
}
@main struct M { static func main() async { await f() } }
1
2
3
bash diag.sh Compat.swift
xcrun swiftc -parse-as-library -swift-version 6 Compat.swift -o x
./x
1
[exit 0]
1
2
a: Result<Int, Error> success(1)
b: Result<Int, Error> success(2)
async 함수 안에서도 await 없이 쓴 동기판은 그대로 동기판으로 골라진다. 기존 코드가 깨지지 않는다.
둘째로, 코드베이스에 이미 같은 이름의 확장이 있는 경우다. 직접 만든 init(catching:) async 가 표준 라이브러리 것과 겹치면 어느 쪽이 쓰이는지 봤다.
Collide.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func asyncWork() async throws -> Int { 2 }
extension Result where Failure == any Error {
init(catching body: () async throws -> Success) async {
print("my own init")
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
func f() async {
let b = await Result { try await asyncWork() }
print("b:", type(of: b), b)
}
@main struct M { static func main() async { await f() } }
1
2
3
bash diag.sh Collide.swift
xcrun swiftc -parse-as-library -swift-version 6 Collide.swift -o x
./x
1
[exit 0]
1
2
my own init
b: Result<Int, Error> success(2)
모호하다는 error 가 없고 내 확장이 골라졌다. 같은 모양의 확장을 이미 가진 프로젝트는 그대로 컴파일된다. 다만 그 확장이 nonisolated(nonsending) 이 아니면 상황이 달라진다. 앞의 Handmade.swift 모양의 확장이 남아 있는 프로젝트에서 라벨 없이 trailing closure 로 부르면 어느 쪽이 골라지는지 보았다.
CollideIso2.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final class Counter { var n = 0 }
func work() async throws -> Int { 1 }
extension Result where Failure == any Error {
init(catching body: () async throws -> Success) async {
print("my own init")
do { self = .success(try await body()) } catch { self = .failure(error) }
}
}
@MainActor final class Model {
let counter = Counter()
func refresh() async {
let r = await Result {
counter.n += try await work()
return counter.n
}
print(r)
}
}
@main struct M { static func main() async { await Model().refresh() } }
1
bash diag.sh CollideIso2.swift
1
2
3
4
5
6
7
8
9
10
11
12
CollideIso2.swift:12:19: error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 | let counter = Counter()
11 | func refresh() async {
12 | let r = await Result {
| |- error: sending value of non-Sendable type '() async throws -> Int' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated value of non-Sendable type '() async throws -> Int' to @concurrent initializer 'init(catching:)' risks causing races in between main actor-isolated and @concurrent uses
13 | counter.n += try await work()
14 | return counter.n
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
내 확장이 골라졌고 @concurrent initializer 라는 note 와 함께 Swift 6 에서 error 가 난다. 라벨이 asyncCatching 인 확장(CollideIso.swift)도 trailing closure 로 부르면 같은 error 가 나서, 라벨이 달라도 trailing closure 호출은 그쪽으로 간다. non-Sendable 상태를 잡지 않는 closure 로 같은 호출을 하는 CollideLabel.swift 는 진단이 없고 실행하면 my own init 이 찍혀 역시 내 확장으로 간다. 그러니 직접 만든 확장이 남아 있는 동안에는 표준 라이브러리판의 nonsending 이 적용되지 않는다. 확장을 지우기 전까지는 Handmade.swift 의 error 가 그대로 따라온다.
Swift 5 모드
-swift-version 5 로 Iso.swift, Basic.swift, Back.swift, Compat.swift, Collide.swift, Typed.swift, Param.swift 를 돌리면 모두 [exit 0] 이다. Overload.swift 는 Swift 6 모드와 같은 error 가 나서 [exit 1] 이고, 이것은 의도된 대조다. 직접 만든 판 Handmade.swift 도 -swift-version 5 로는 진단이 없고, -strict-concurrency=complete 를 주면 Swift 6 의 error 와 같은 문장의 warning 이 나온다.
1
bash diag.sh -swift-version 5 -strict-concurrency=complete Handmade.swift
1
2
3
4
5
6
7
8
9
10
11
12
Handmade.swift:13:19: warning: sending value of non-Sendable type '() async throws -> Int' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
11 | let counter = Counter()
12 | func refresh() async {
13 | let r = await Result(asyncCatching: {
| |- warning: sending value of non-Sendable type '() async throws -> Int' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated value of non-Sendable type '() async throws -> Int' to @concurrent initializer 'init(asyncCatching:)' risks causing races in between main actor-isolated and @concurrent uses
14 | counter.n += try await work()
15 | return counter.n
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 0]
직접 만든 확장 때문에 Swift 6 로 옮기다 걸린 코드라면, 확장을 지워 호출이 표준 라이브러리판으로 가게 하는 것이 고치는 길이다. 확장이 nonisolated(nonsending) 이 되도록 고쳐도 된다. OnlyInit.swift 가 그 경우다.
옛 OS 에서 쓰기
@_alwaysEmitIntoClient 라 back-deploy 된다는 제안서의 문장을 -target 으로 쟀다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target x86_64-apple-macos10.15 Back.swift
종료 코드는 0 이고 진단이 없다. Iso.swift 도 같은 타깃으로 종료 코드 0 이다. arm64-apple-macos14 로 Basic.swift 와 Iso.swift 를 컴파일해도 종료 코드 0 이다. 컴파일만이 아니라 실제로 옛 OS 타깃으로 빌드해서 실행도 했다.
1
2
3
xcrun swiftc -parse-as-library -swift-version 6 -target arm64-apple-macos12 Iso.swift -o x
./x
nm -u x | grep Result
1
2
3
4
main model: success(1) isolation: Swift.MainActor
actor store: success(1)
_$ss6ResultOMa
_$ss6ResultOMn
1
2
3
xcrun swiftc -parse-as-library -swift-version 6 -target arm64-apple-macos11 Back.swift -o x
./x
nm -u x | grep Result
1
2
token 9
_$ss6ResultOMa
nm -u 는 실행 파일이 밖에서 가져오는 심볼을 보여 주고, grep Result 로 Result 관련만 걸렀다. 남은 것은 Result 타입의 metadata accessor(OMa)와 nominal type descriptor(OMn)이고, 새 초기화 함수의 심볼은 없다. 초기화 함수 본문이 앱 바이너리 안에 들어와 있다는 뜻이다. 그래서 interface 의 macOS 10.15 아래에서도 if #available 로 갈라 쓸 필요가 없다. Iso.swift 쪽에는 OMn 이 하나 더 있고, Back.swift 는 OMa 하나뿐이다.
정리
Result.init(catching:)의 비동기판이_Concurrency모듈에@available(macOS 10.15, ...),@_alwaysEmitIntoClient,where Success : ~Copyable,nonisolated(nonsending)으로 들어왔다.await Result { try await work() }로 성공과 실패를 값에 담는다. 던지지 않는 closure 는Result<T, Never>다.- typed throws 는 자동으로 보존되지 않는다. closure 가
any Error로 추론되기 때문이고 동기판도 같다.() async throws(Boom) -> String으로 시그니처를 적으면Result<String, Boom>이 된다. - body 는 호출자 isolation 에서 돈다.
@MainActorclass 와 actor 안에서 non-Sendable 상태를 그대로 쓴다. 직접 만든 판은@concurrent로 취급되어sendingerror 가 나고,NonisolatedNonsendingByDefault를 켜거나 초기화 함수에nonisolated(nonsending)을 붙이면 통과한다. 결과Result는 호출자 isolation 에 묶여서 non-SendableSuccess일 때는Task.detached로 직접 보낼 수 없다. - 선택은 closure 본문이 정한다. 동기 closure 에
await를 붙이면 warning, 비동기 closure 에await를 빼면 error 다. - 순수한 추가라 기존 코드가 깨지지 않고, 같은 이름의 직접 만든 확장이 있어도 모호하다는 error 가 없다.
@_alwaysEmitIntoClient라macos12와macos11타깃으로 빌드해서 실행하면 새 초기화 함수의 심볼 없이 돈다.
관련 글
- [SE-0461] Run nonisolated async functions on the caller’s actor by default:
nonisolated(nonsending)의 규칙. 이 글의 중심이 되는 속성 - [SE-0430] sending parameter and result values: 직접 만든 판의 error 가 나온
sending규칙 - [SE-0414] Region based Isolation:
Region.swift의 note 가 설명하는 region isolation 진단 - [SE-0528] Continuation: Safe and Performant Async Continuations: 같은 묶음의 다른 제안서
