포스트

[SE-0520] Discardable result use in Task initializers

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


제안서 정보


한 줄 요약

결과를 받아 두지 않은 Task { try boom() } 처럼 오류를 던질 수 있는 unstructured task 를 만들면, Swift 6.4 컴파일러가 [#NoUseUnstructuredThrowingTask] warning 을 낸다. 오류를 던지지 않는 Task { } 는 지금처럼 조용하다. 새 API 도 새 attribute 도 없고, Task.init, detached, immediate, immediateDetached 의 @discardableResult 는 그대로다. 컴파일러가 task 의 Failure 가 Never 인지를 보고 진단을 더한다. 이 글은 어떤 줄에서 warning 이 나고 어떤 줄은 조용한지, 끄고 키우는 방법은 무엇인지를 컴파일한 출력으로 정리한다.


어떤 문제였나

Swift 의 Task { ... } 는 가장 자주 쓰는 동시성 문법 중 하나다. 그런데 이 문법에는 오래된 함정이 하나 있었다. closure 안에서 던진 오류가 아무 데도 닿지 않고 사라져도 컴파일러가 아무 말을 하지 않는다는 점이다. 이 절에서는 그 함정이 어떻게 생기는지부터 본다.


던진 오류가 사라지는 경우

오류를 던지는 함수를 Task 안에서 부르고 그 task 를 버리는 코드와, 같은 task 를 받아 두고 결과를 꺼내 보는 코드를 나란히 놓고 실행했다.

Swallow.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Boom: Error {}
func boom() throws { print("boom() throws"); throw Boom() }

@main struct M {
  static func main() async {
    _ = Task { try boom() }
    try? await Task.sleep(for: .milliseconds(50))
    print("Yay!")
    let task = Task { try boom() }
    do {
      try await task.value
    } catch {
      print("caught \(error)")
    }
    let r = await task.result
    print("result \(r)")
  }
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 Swallow.swift -o x
./x
1
2
3
4
5
boom() throws
Yay!
boom() throws
caught Boom()
result failure(x.Boom())

첫 task 는 _ = 로 버렸다. boom() throws 가 찍혔으니 closure 는 실제로 실행되었고 Boom 을 던졌지만, 그 오류를 본 사람은 아무도 없다. 프로그램은 Yay! 를 찍고 계속 간다. 두 번째 task 는 task 에 담았고, try await task.value 가 같은 오류를 caught Boom() 으로 꺼내 주었다. 마지막 줄은 task.result 로 읽은 결과다. failure(x.Boom()) 의 x 는 모듈 이름으로, 출력 파일 이름이 x 라서 그렇게 찍혔다. 이 코드를 세 번 돌렸을 때 출력은 같았다. 첫 Task 뒤에 50ms 를 재워 둔 덕분에 boom() throws 가 Yay! 보다 먼저 나온다.

_ = 로 일부러 버리는 것은 의도가 코드에 남으니 문제가 없다. 문제는 _ = 없이도 똑같이 버려진다는 데 있다.

Task 와 value, result

Task는 비동기 작업 하나를 새로 시작하는 타입이다. Task { ... } 처럼 closure 를 넘기면 현재 task 의 자식이 아닌 새 task 가 만들어지고, 이런 task 를 unstructured task 라고 부른다. 부모가 끝나기를 기다려 주지도 않고 부모의 취소를 받지도 않는다. 제네릭 Task<Success, Failure> 에서 Success 는 closure 의 반환 타입이고 Failure 는 던질 수 있는 오류 타입이다. 오류를 던지지 않으면 Failure 는 Never 가 된다.

  1. Task { try boom() } 는 closure 가 try 를 쓰니 Task<(), any Error> 가 된다.
  2. task.value 는 task 가 끝나기를 기다려 결과 값을 돌려준다. task 가 오류를 던졌다면 그 오류를 다시 던지므로 try await 로 받아야 한다.
  3. task.result 는 같은 결과를 Result<Success, Failure> 로 감싸서 돌려준다. 던지지 않으니 try 없이 await 만 쓴다.

Task.sleep(for:)는 지정한 시간만큼 현재 task 를 재운다. 여기서는 버려진 task 가 먼저 실행될 시간을 주는 데 썼다.


@discardableResult 란?

Swift 는 값을 돌려주는 함수를 불러 놓고 그 값을 쓰지 않으면 warning 을 낸다. 반환값을 무심코 놓친 것일 수 있어서다. 값을 버려도 괜찮은 함수는 선언에 @discardableResult 를 붙여서 그 warning 을 끈다. 아주 작은 예로 확인했다.

Discard.swift

1
2
3
4
5
6
7
8
func plain() -> Int { 1 }
@discardableResult func quiet() -> Int { 1 }

func f() {
  plain()
  quiet()
  _ = plain()
}
1
2
3
4
5
6
7
8
9
10
Discard.swift:5:3: warning: result of call to 'plain()' is unused [#NoUsage]
3 | 
4 | func f() {
5 |   plain()
  |   `- warning: result of call to 'plain()' is unused [#NoUsage]
6 |   quiet()
7 |   _ = plain()

[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>
[exit 0]

plain() 은 warning 을 받았고 @discardableResult 가 붙은 quiet() 와 _ = plain() 은 조용하다. _ = 는 “이 값을 일부러 버린다” 는 뜻이라 어떤 함수에서도 warning 을 끈다.

Task 의 initializer 는 값(Task 인스턴스)을 돌려주는 함수처럼 취급되고, 지금까지 모든 initializer 에 @discardableResult 가 붙어 있었다. 그래서 Task { ... } 를 문장으로 쓰면 어떤 closure 든 warning 이 없었다. 6.4 SDK 의 _Concurrency interface 로 확인했다.

1
2
F=$(xcrun --show-sdk-path)/usr/lib/swift/_Concurrency.swiftmodule/arm64e-apple-macos.swiftinterface
sed -n '3763,3940p' $F | grep -E "^extension|@discardableResult|public (init|static func detached)" | cut -c1-96
1
2
3
4
5
6
7
8
9
10
11
12
extension _Concurrency::Task where Failure == Swift::Never {
  @discardableResult
  @_alwaysEmitIntoClient public init(name: Swift::String? = nil, priority: _Concurrency::TaskPri
extension _Concurrency::Task where Failure == any Swift::Error {
  @discardableResult
  @_alwaysEmitIntoClient public init(name: Swift::String? = nil, priority: _Concurrency::TaskPri
extension _Concurrency::Task where Failure == Swift::Never {
  @discardableResult
  @_alwaysEmitIntoClient public static func detached(name: Swift::String? = nil, priority: _Conc
extension _Concurrency::Task where Failure == any Swift::Error {
  @discardableResult
  @_alwaysEmitIntoClient public static func detached(name: Swift::String? = nil, priority: _Conc

Failure == Never 판과 Failure == any Error 판이 따로 있고, 둘 다 @discardableResult 다. immediate 와 immediateDetached 도 같은 모양으로 두 판씩 있다. 6.4 SDK 의 interface 가 이런 구조다.


그럼 왜 버려도 된다고 했나

Task { ... } 문법은 원래 fire-and-forget, 곧 시작만 하고 잊어버리는 용도로 만든 것이다. 제안서도 이 점을 문제의 출발점으로 든다. 오류가 어떻게 되는지에 대한 고려가 충분하지 않았고, 그 결과 Swift 의 오류 처리 모델과 어긋난 채로 남았다.

이 어긋남은 포럼에서 여러 번 올라왔다. 제안서는 Task initializer with throwing closure swallows error 를 비롯한 세 스레드를 들고, 그중 어느 것도 완결된 제안으로 이어지지 못했다고 쓴다. 이번 pitch 에서 ktoso 는 큰 코드베이스를 뒤져 봤다고 밝혔다. 특히 UI 코드의 Button { Task { ... } } 같은 모양이 많고, 코드 한가운데에 낀 Task { } 도 있다는 것이다. fire-and-forget 을 가리키는 다른 문법이 없으니 이 구분은 어렵다고 했다(#5, 2026-02-13). Andropov 는 큰 프로젝트에서 Task { ... } 를 2600번쯤 썼는데 앞에 대입이 붙은 것은 300개쯤이었다고 센 결과를 올렸다(#6). 버리는 쪽이 압도적으로 흔하다는 이야기다.


무엇이 바뀌나

바뀌는 것은 컴파일러의 진단 하나다. @discardableResult 를 떼는 것이 아니라, task 를 만든 문장의 결과가 쓰이지 않고 task 의 Failure 가 Never 가 아니면 [#NoUseUnstructuredThrowingTask] warning 을 낸다. 아래에서는 어떤 줄이 warning 을 받는지, 어떤 API 이름이 진단에 나오는지, 어디까지가 대상인지, 끄고 키우는 방법은 무엇인지를 하나씩 잰다.


어떤 줄이 warning 을 받나

제안서의 표를 그대로 옮기지 않고, 같은 의도를 Swift 6.4 컴파일러에 직접 물었다. Task.detached, Task.immediate, Task.immediateDetached 까지 한 파일에 넣었다.

Warn.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Boom: Error {}
func boom() throws { throw Boom() }
func typed() throws(Boom) { throw Boom() }

func cases() async {
  Task { print("plain") }
  Task { try boom() }
  Task { () throws(Boom) in try typed() }
  Task { () throws(Never) in print("never") }
  Task.detached { try boom() }
  Task.immediate { try boom() }
  Task.immediateDetached { try boom() }
  Task { 42 }
  Task { try boom(); return 42 }
  _ = Task { try boom() }
  let t = Task { try boom() }
  _ = t
  await withTaskGroup(of: Void.self) { g in
    g.addTask { }
  }
}
@main struct M { static func main() async { await cases() } }
1
bash diag.sh Warn.swift

diag.sh 는 xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 를 감싼 스크립트다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Warn.swift:7:3: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 5 | func cases() async {
 6 |   Task { print("plain") }
 7 |   Task { try boom() }
   |   |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 8 |   Task { () throws(Boom) in try typed() }
 9 |   Task { () throws(Never) in print("never") }

Warn.swift:8:3: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 6 |   Task { print("plain") }
 7 |   Task { try boom() }
 8 |   Task { () throws(Boom) in try typed() }
   |   |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 9 |   Task { () throws(Never) in print("never") }
10 |   Task.detached { try boom() }

Warn.swift:10:8: warning: unstructured throwing task created by 'detached(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 8 |   Task { () throws(Boom) in try typed() }
 9 |   Task { () throws(Never) in print("never") }
10 |   Task.detached { try boom() }
   |        |- warning: unstructured throwing task created by 'detached(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |        `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
11 |   Task.immediate { try boom() }
12 |   Task.immediateDetached { try boom() }

Warn.swift:11:8: warning: unstructured throwing task created by 'immediate(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 9 |   Task { () throws(Never) in print("never") }
10 |   Task.detached { try boom() }
11 |   Task.immediate { try boom() }
   |        |- warning: unstructured throwing task created by 'immediate(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |        `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
12 |   Task.immediateDetached { try boom() }
13 |   Task { 42 }

Warn.swift:12:8: warning: unstructured throwing task created by 'immediateDetached(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
10 |   Task.detached { try boom() }
11 |   Task.immediate { try boom() }
12 |   Task.immediateDetached { try boom() }
   |        |- warning: unstructured throwing task created by 'immediateDetached(name:priority:executorPreference:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |        `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
13 |   Task { 42 }
14 |   Task { try boom(); return 42 }

Warn.swift:14:3: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
12 |   Task.immediateDetached { try boom() }
13 |   Task { 42 }
14 |   Task { try boom(); return 42 }
   |   |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
15 |   _ = Task { try boom() }
16 |   let t = Task { try boom() }

[#NoUseUnstructuredThrowingTask]: <https://docs.swift.org/compiler/documentation/diagnostics/no-use-throwing-unstructured-task>
[exit 0]

warning 이 나는 줄은 7, 8, 10, 11, 12, 14 이렇게 여섯 개다. 하나씩 읽으면 이렇다.

줄코드결과
6Task { print("plain") }조용함
7Task { try boom() }warning
8Task { () throws(Boom) in try typed() }warning
9Task { () throws(Never) in print("never") }조용함
10Task.detached { try boom() }warning
11Task.immediate { try boom() }warning
12Task.immediateDetached { try boom() }warning
13Task { 42 }조용함
14Task { try boom(); return 42 }warning
15, 16_ = Task { ... }, let t = Task { ... }조용함
19g.addTask { }조용함

던지는 task 를 받아 두지 않은 칸에만 warning 이 나고 나머지 세 칸은 조용하다는 것을 보인 표

판정 기준은 두 가지다. 컴파일러가 고른 initializer 가 던질 수 있는 판(Failure 가 Never 가 아닌 판)인가, 그리고 만든 task 를 문장 끝에서 그냥 버리는가. closure 본문이 실제로 던지는지가 아니라 고른 판의 operation 타입이 throws 인지를 본다. 14번처럼 Int 를 돌려주는 task 도 던지기만 하면 warning 이다. 13번처럼 값을 돌려주기만 하고 던지지 않으면 조용하다. 15번과 16번은 task 를 _ 나 let 에 받았으니 어느 쪽이든 조용하다. 19번의 g.addTask 는 task group 의 child 를 만드는 문법이고 Void 를 돌려줘서 버릴 task 핸들이 없으므로 이 진단의 대상이 아니다.

여섯 줄 모두 같은 문장과 note 가 붙는다. 첫 줄은 task 가 오류를 삼킬 수 있다는 사실을, note 는 풀 수 있는 두 가지 길(task 안에서 오류를 처리하거나 task 값을 명시적으로 저장하거나 버리기)을 알려 준다. pitch 에서 Andropov 가 기본 “result of call is unused” 진단에 오류를 삼킬 수 있다는 설명을 더하면 좋겠다고 했는데(#6), 그 방향이 이 문장으로 구현된 셈이다. 진단 끝의 [#NoUseUnstructuredThrowingTask] 는 diagnostic group 이름이고, 링크는 컴파일러 문서 페이지다.

줄마다 달라지는 API 이름

진단 문장 속 init(name:priority:operation:), detached(name:priority:operation:), immediate(name:priority:executorPreference:operation:), immediateDetached(name:priority:executorPreference:operation:) 는 컴파일러가 고른 overload 의 전체 이름이다. 그래서 진단만 봐도 어느 API 로 만든 task 인지 알 수 있다. 각 API 는 이렇게 다르다.

  • Task.init(name:priority:operation:)는 현재 actor 와 task-local 값을 이어받는 task 를 만든다.
  • Task.detached 는 현재 actor 와 task-local 값을 이어받지 않는 task 를 만든다.
  • Task.immediate 는 SE-0472 로 들어온 API 로, 호출한 쪽의 실행 맥락에서 첫 suspension 지점까지 동기적으로 먼저 돈다. immediateDetached 는 그것의 detached 짝이다. 이 둘은 SE-0472 글에서 자세히 다룬다.

name: 파라미터는 SE-0469 로 들어온 task 이름이다. 진단이 이름 있는 판을 가리키는 것은 이 시그니처가 지금의 Task.init 이어서다.


executorPreference 판도 대상인가

SE-0417 로 들어온 executorPreference: 판도 같은 진단을 받는지 More.swift 로 확인했다. 이 파일에는 오류를 task 안에서 처리하는 경우와 함수가 task 를 돌려주는 경우도 함께 넣었다.

More.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Boom: Error {}
func boom() throws { throw Boom() }
func typed() throws(Boom) { throw Boom() }

func make() -> Task<Void, any Error> { Task { try boom() } }
@discardableResult func makeD() -> Task<Void, any Error> { Task { try boom() } }

func cases() async {
  Task { try? boom() }
  Task { do { try boom() } catch { print(error) } }
  make()
  makeD()
  Task(executorPreference: globalConcurrentExecutor) { try boom() }
  Task.detached(executorPreference: globalConcurrentExecutor) { try boom() }
  let x = Task { () throws(Boom) in try typed() }
  await withThrowingTaskGroup(of: Void.self) { g in
    g.addTask { try boom() }
  }
}
@main struct M { static func main() async { await cases() } }
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
More.swift:11:3: warning: result of call to 'make()' is unused [#NoUsage]
 9 |   Task { try? boom() }
10 |   Task { do { try boom() } catch { print(error) } }
11 |   make()
   |   `- warning: result of call to 'make()' is unused [#NoUsage]
12 |   makeD()
13 |   Task(executorPreference: globalConcurrentExecutor) { try boom() }

More.swift:13:3: warning: unstructured throwing task created by 'init(name:executorPreference:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
11 |   make()
12 |   makeD()
13 |   Task(executorPreference: globalConcurrentExecutor) { try boom() }
   |   |- warning: unstructured throwing task created by 'init(name:executorPreference:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
14 |   Task.detached(executorPreference: globalConcurrentExecutor) { try boom() }
15 |   let x = Task { () throws(Boom) in try typed() }

More.swift:14:8: warning: unstructured throwing task created by 'detached(name:executorPreference:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
12 |   makeD()
13 |   Task(executorPreference: globalConcurrentExecutor) { try boom() }
14 |   Task.detached(executorPreference: globalConcurrentExecutor) { try boom() }
   |        |- warning: unstructured throwing task created by 'detached(name:executorPreference:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |        `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
15 |   let x = Task { () throws(Boom) in try typed() }
16 |   await withThrowingTaskGroup(of: Void.self) { g in

More.swift:15:7: warning: initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it [#NoUsage]
13 |   Task(executorPreference: globalConcurrentExecutor) { try boom() }
14 |   Task.detached(executorPreference: globalConcurrentExecutor) { try boom() }
15 |   let x = Task { () throws(Boom) in try typed() }
   |       `- warning: initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it [#NoUsage]
16 |   await withThrowingTaskGroup(of: Void.self) { g in
17 |     g.addTask { try boom() }

[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>
[#NoUseUnstructuredThrowingTask]: <https://docs.swift.org/compiler/documentation/diagnostics/no-use-throwing-unstructured-task>
[exit 0]

13번과 14번이 executorPreference: 판이다. 진단은 init(name:executorPreference:priority:operation:) 와 detached(name:executorPreference:priority:operation:) 로 이름을 달리해 나온다. 같은 task 를 만드는 API 라면 executor 를 어떻게 정하든 대상이다. executor 선호는 SE-0417 글에서 다룬다.

9번과 10번은 task 안에서 오류를 처리하니(try? 로 없애거나 do/catch 로 잡는다) warning 이 없다. 두 closure 모두 오류를 던지지 않아서 Failure 가 Never 인 판이 골라진다. 다만 타입은 다르다. 아래 Types.swift 로 실행해 보면 try? 판은 Task<Optional<()>, Never> 이고 do/catch 판은 Task<(), Never> 다. try? 는 Void 를 Void? 로 바꾸기 때문이다.

Types.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Boom: Error {}
func boom() throws { throw Boom() }
func check<T>(_ x: T) { print(type(of: x)) }
func cases() {
  let a = Task { try? boom() }
  check(a)
  let b = Task { do { try boom() } catch { print(error) } }
  check(b)
  let c = { Task { try boom() } }
  check(c)
  var set = Set([1, 2, 3])
  let d = Task { set.insert(4) }
  check(d)
  let (_, continuation) = AsyncStream.makeStream(of: Int.self)
  let e = Task { continuation.yield(42) }
  check(e)
  let f: Task<(), Never> = Task { try? boom() }
  _ = f
}
@main struct M { static func main() { cases() } }
1
2
xcrun swiftc -parse-as-library -swift-version 6 Types.swift -o x
./x
1
2
3
4
5
6
Task<Optional<()>, Never>
Task<(), Never>
Boom()
() -> Task<(), Error>
Task<(inserted: Bool, memberAfterInsert: Int), Never>
Task<YieldResult, Never>

첫 줄이 try? 판, 둘째 줄이 do/catch 판이다. () -> Task<(), Error> 는 앞에서 본 let c = { Task { try boom() } } 의 타입이다. 마지막 두 줄은 뒤에서 볼 Set.insert 와 continuation.yield 의 task 타입이다. Boom() 은 do/catch task 가 다른 스레드에서 찍은 것이라 여섯 번 돌렸을 때 세 번째 줄과 네 번째 줄에 번갈아 나왔다.

11번과 12번은 대조군이다. make() 는 Task<Void, any Error> 를 돌려주는 평범한 함수라서 새 진단이 아니라 기본 result of call to 'make()' is unused [#NoUsage] 를 받는다. @discardableResult 를 붙인 makeD() 는 조용하다. 새 진단은 Task initializer 에만 걸려 있고 내가 만든 함수에는 걸리지 않는다.

15번의 let x = ... 는 새 진단이 아니라 “x 를 쓰지 않았다” 는 [#NoUsage] warning 이 났다. 이 코드는 task 를 let 에 받아서 NoUseUnstructuredThrowingTask 는 막았지만, 받은 변수를 쓰지 않으면 다른 warning 이 따로 있다는 뜻이다. 16번부터의 g.addTask { try boom() } 는 throwing task group 안에서 던지는 child 인데도 조용하다. 이 진단은 unstructured task 만 본다.


attribute 가 아닌 컴파일러 진단

지금까지 본 것을 합치면 한 가지가 보인다. Failure == any Error 판의 @discardableResult 는 그대로인데 warning 이 나온다. 그러니 이 warning 은 attribute 를 떼서 생기는 것이 아니다. 컴파일러가 “task 를 만드는 initializer 인데, 결과가 쓰이지 않았고, closure 가 던진다” 는 조건을 따로 검사해서 낸다.

이 조건은 본문이 아니라 고른 initializer 의 operation 타입을 본다. Criterion.swift 로 확인했다.

Criterion.swift

1
2
3
4
5
6
7
8
9
10
11
struct Boom: Error {}
func boom() throws { throw Boom() }
func plain() {}
func cases() {
  Task<Void, any Error> { plain() }
  Task<Void, any Error>(operation: plain)
  let op: @Sendable () async throws -> Void = { try boom() }
  Task(operation: op)
  Task { () throws in print("x") }
  Task.runDetached { try boom() }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Criterion.swift:5:23: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 3 | func plain() {}
 4 | func cases() {
 5 |   Task<Void, any Error> { plain() }
   |                       |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |                       `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 6 |   Task<Void, any Error>(operation: plain)
 7 |   let op: @Sendable () async throws -> Void = { try boom() }

Criterion.swift:6:23: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 4 | func cases() {
 5 |   Task<Void, any Error> { plain() }
 6 |   Task<Void, any Error>(operation: plain)
   |                       |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |                       `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 7 |   let op: @Sendable () async throws -> Void = { try boom() }
 8 |   Task(operation: op)

Criterion.swift:8:3: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 6 |   Task<Void, any Error>(operation: plain)
 7 |   let op: @Sendable () async throws -> Void = { try boom() }
 8 |   Task(operation: op)
   |   |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 9 |   Task { () throws in print("x") }
10 |   Task.runDetached { try boom() }

Criterion.swift:9:3: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 7 |   let op: @Sendable () async throws -> Void = { try boom() }
 8 |   Task(operation: op)
 9 |   Task { () throws in print("x") }
   |   |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |   `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
10 |   Task.runDetached { try boom() }
11 | }

Criterion.swift:10:8: warning: 'runDetached(priority:operation:)' is deprecated: `Task.runDetached` was replaced by `Task.detached` and will be removed shortly. [#DeprecatedDeclaration]
 8 |   Task(operation: op)
 9 |   Task { () throws in print("x") }
10 |   Task.runDetached { try boom() }
   |        `- warning: 'runDetached(priority:operation:)' is deprecated: `Task.runDetached` was replaced by `Task.detached` and will be removed shortly. [#DeprecatedDeclaration]
11 | }
12 | 

[#DeprecatedDeclaration]: <https://docs.swift.org/compiler/documentation/diagnostics/deprecated-declaration>
[#NoUseUnstructuredThrowingTask]: <https://docs.swift.org/compiler/documentation/diagnostics/no-use-throwing-unstructured-task>
[exit 0]

5번 줄 Task<Void, any Error> { plain() } 은 본문이 아무것도 던지지 않는데도 warning 이다. 타입을 Task<Void, any Error> 로 적어 던질 수 있는 판을 골랐기 때문이다. 6번 줄 (operation: plain) 도 같다. 8번 줄은 던지는 함수 값을 operation: 으로 넘긴 경우이고, 9번 줄 Task { () throws in print("x") } 는 본문이 print 뿐이어도 throws 를 적었으니 warning 이다. 10번 줄 Task.runDetached 는 deprecated 선언이라 deprecation warning 만 나고 이 진단은 나지 않는다. 오류 타입이 무엇이든 던질 수 있는 판이면 따라붙는다. 아래는 typed throws 로 Boom 만 던지는 closure 의 task 타입을 컴파일러에 물어본 것이다.

TypedFailure.swift

1
2
3
4
5
6
7
8
9
struct Boom: Error {}
func typed() throws(Boom) { throw Boom() }

func show() {
  let a = Task { () throws(Boom) in try typed() }
  let ok: Task<Void, any Error> = a
  let typedFailure: Task<Void, Boom> = a
  _ = (ok, typedFailure)
}
1
2
3
4
5
6
7
8
9
TypedFailure.swift:7:40: error: cannot assign value of type 'Task<(), any Error>' to type 'Task<Void, Boom>'
 5 |   let a = Task { () throws(Boom) in try typed() }
 6 |   let ok: Task<Void, any Error> = a
 7 |   let typedFailure: Task<Void, Boom> = a
   |                                        |- error: cannot assign value of type 'Task<(), any Error>' to type 'Task<Void, Boom>'
   |                                        `- note: arguments to generic parameter 'Failure' ('any Error' and 'Boom') are expected to be equal
 8 |   _ = (ok, typedFailure)
 9 | }
[exit 1]

Task { () throws(Boom) in ... } 의 타입은 Task<(), any Error> 다. Task<Void, any Error> 에는 대입되고 Task<Void, Boom> 에는 대입되지 않는다. 6.4 의 Task.init 은 Failure 에 대해 Never 판과 any Error 판 둘뿐이고, 오류 타입이 Boom 으로 남는 generic 판은 없다. 진단은 이 any Error 판을 대상으로 한다. 앞의 8번 줄이 warning 을 받은 이유다.

리뷰에서 ktoso 가 구현을 설명한 것이 이 구조와 맞닿아 있다(#3, 2026-03-17). attribute 를 하나 새로 만들어서, 파라미터에 closure 가 있고 그 closure 가 던지면 rethrow 하지 않더라도 결과를 버리면 안 된다고 보는 규칙이라고 했다. 이것을 정식 attribute 로 일반화할 수도 있다고 덧붙였다.


단일 표현식 함수와 closure 안의 Task

fire-and-forget 이 가장 자주 나오는 자리는 단일 표현식으로 된 함수와 closure 다. Button 의 action 처럼 () -> Void 를 받는 자리가 그렇다. 반환 타입이 Void 인 곳에서 단일 표현식이 Task 를 만들면 어떻게 되는지 SingleExpr.swift 로 확인했다.

SingleExpr.swift

1
2
3
4
5
6
7
8
9
10
11
struct Boom: Error {}
func boom() throws { throw Boom() }

func onTap() { Task { try boom() } }
func run(_ body: () -> Void) { body() }
func use() {
  run { Task { try boom() } }
  let c = { Task { try boom() } }
  _ = c
}
@main struct M { static func main() { use(); onTap() } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
SingleExpr.swift:4:16: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 2 | func boom() throws { throw Boom() }
 3 | 
 4 | func onTap() { Task { try boom() } }
   |                |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |                `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 5 | func run(_ body: () -> Void) { body() }
 6 | func use() {

SingleExpr.swift:7:9: warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
 5 | func run(_ body: () -> Void) { body() }
 6 | func use() {
 7 |   run { Task { try boom() } }
   |         |- warning: unstructured throwing task created by 'init(name:priority:operation:)' is not used, which may accidentally ignore errors thrown inside the task [#NoUseUnstructuredThrowingTask]
   |         `- note: to silence this warning, handle the error inside the task, or store/discard the task value explicitly
 8 |   let c = { Task { try boom() } }
 9 |   _ = c

[#NoUseUnstructuredThrowingTask]: <https://docs.swift.org/compiler/documentation/diagnostics/no-use-throwing-unstructured-task>
[exit 0]

func onTap() { Task { try boom() } } (4번 줄) 는 본문이 한 줄이어도 warning 을 받는다. run { Task { try boom() } } (7번 줄) 도 받는다. run 이 () -> Void closure 를 받으니 그 closure 의 값은 버려지기 때문이다. 8번 줄의 let c = { Task { try boom() } } 는 조용하다. closure 가 Task 를 돌려주는 타입(() -> Task<(), any Error>)이라서 task 가 버려지는 것이 아니라 c 의 반환값이 되기 때문이다. 그 task 를 누가 받을지는 c 를 부르는 쪽의 몫이다.


결과를 내는 task 의 경우

던지지는 않지만 값을 돌려주는 task 는 조용하다. 앞의 13번 줄 Task { 42 } 가 그랬다. 포럼에서는 이 경우도 막자는 이야기가 길게 이어졌다. 그래서 pitch 가 보여 준 두 예를 NonVoid.swift 로 확인했다.

NonVoid.swift

1
2
3
4
5
6
7
8
9
10
11
func cases() {
  var set = Set([1, 2, 3])
  Task {
    set.insert(4)
  }
  let (_, continuation) = AsyncStream.makeStream(of: Int.self)
  Task {
    continuation.yield(42)
  }
  Task { 42 }
}
1
[exit 0]

Set.insert 는 (inserted: Bool, memberAfterInsert: Int) 를 돌려주고, AsyncStream.Continuation.yield 는 YieldResult 를 돌려준다. 둘 다 @discardableResult 함수이고 Task { ... } 의 closure 는 단일 표현식이라 그 값이 task 의 Success 로 올라간다. 이 task 들은 던지지 않으므로 이번 진단도 기존 진단도 없다. 수락 공지가 “결과를 내는 task 에 warning 을 주는 것은 별개 문제” 라고 따로 둔 곳이 바로 이 자리다.


경고를 끄고 키우는 방법

task 를 받아 두거나(let) 버리겠다고 적거나(_ =) 오류를 task 안에서 처리하면 진단이 사라진다. 앞의 측정들이 그 방법이다. 컴파일러 옵션으로 진단을 직접 다룰 수도 있다. 이 warning 은 diagnostic group 에 속해서, group 이름으로 error 로 올리거나 되돌릴 수 있다. warning 을 group 별로 제어하는 옵션은 SE-0443 로 들어왔다. 앞의 Warn.swift 에 그대로 적용해 보았다. 먼저 이 group 만 error 로 올렸다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -Werror NoUseUnstructuredThrowingTask Warn.swift 2>&1 | grep -oE '^Warn.swift:[0-9]+:[0-9]+: (error|warning)'
1
2
3
4
5
6
Warn.swift:7:3: error
Warn.swift:8:3: error
Warn.swift:10:8: error
Warn.swift:11:8: error
Warn.swift:12:8: error
Warn.swift:14:3: error

여섯 줄이 모두 error 가 되었다. 다음은 모든 warning 을 error 로 올리면서 이 group 만 warning 으로 되돌렸다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -warnings-as-errors -Wwarning NoUseUnstructuredThrowingTask Warn.swift 2>&1 | grep -oE '^Warn.swift:[0-9]+:[0-9]+: (error|warning)'
1
2
3
4
5
6
Warn.swift:7:3: warning
Warn.swift:8:3: warning
Warn.swift:10:8: warning
Warn.swift:11:8: warning
Warn.swift:12:8: warning
Warn.swift:14:3: warning

여섯 줄이 warning 으로 남았다. -warnings-as-errors 만 주면 어떻게 되는지도 봤다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -warnings-as-errors Warn.swift 2>&1 | grep -oE '^Warn.swift:[0-9]+:[0-9]+: (error|warning)'
1
2
3
4
5
6
Warn.swift:7:3: error
Warn.swift:8:3: error
Warn.swift:10:8: error
Warn.swift:11:8: error
Warn.swift:12:8: error
Warn.swift:14:3: error

모든 warning 을 error 로 올리는 설정에서는 이 진단도 error 다. pitch 에서 Jon_Shier 가 우려한 부분이 이것이다(#3, 2026-02-13). 아래에 따로 썼다. 반대로 -suppress-warnings 는 warning 을 모두 끈다.

1
bash diag.sh -suppress-warnings Warn.swift
1
[exit 0]

진단이 하나도 나오지 않고 [exit 0] 만 찍힌다.

컴파일러 문서에서 안내하는 길

진단 끝에 붙은 링크는 컴파일러가 가진 진단 문서를 가리킨다. 툴체인의 share/doc/swift/diagnostics/no-use-throwing-unstructured-task.md 에 같은 문서가 있고 온라인 문서에서도 읽을 수 있다. 이 문서는 먼저 문제를 한 문장으로 설명한다. 던지는 unstructured task 를 저장하거나 버리지 않으면 그 task 의 오류가 조용히 무시된다는 것이다. 그리고 두 가지 길을 보여 준다. 하나는 task 를 저장하고 try await task.value 로 오류를 확인하는 것이고, 다른 하나는 _ = Task { ... } 로 명시적으로 버리는 것이다.

문서에는 “unstructured task 를 취소하기” 절도 있다. 참조를 들고 있으면 task 를 명시적으로 취소할 수 있다는 설명이다. 문서는 참조를 들고 있을 이유로 취소도 든다. KeithBauerANZ 가 pitch 에서 같은 점을 짚었다. 받아 두지 않은 task 는 취소할 방법이 없다는 것이다(#23, 2026-02-16).


스레드에서 오간 이야기

pitch 는 2026-02-13 부터 03-27 까지, 리뷰는 2026-03-16 부터 03-30 까지 열렸다. 논점은 크게 둘이었다. 하나는 어디까지 warning 으로 잡을 것인가이고, 다른 하나는 어떤 장치로 잡을 것인가다. 시간순으로 짚는다.

pitch 의 첫 모양 (2026-02-13)

ktoso 는 pitch 를 열면서(#1) Task.init 과 그 친구들에서 오류를 던지는 판의 @discardableResult 를 떼자고 했다. Failure == Never 판에는 붙여 두고, 나머지 판에서는 떼는 overload 모양이었다. 이미 typed throws 를 이 API 들에 적용했으니 필요한 변경은 attribute 를 빼는 것뿐이라고 했다.

KeithBauerANZ 는 그 정도로는 부족하다고 했다. Task<Void, Never> 를 제외한 모든 initializer 에서 뗄 것을 주장하며, 던지거나 값을 돌려주는 task 를 버리는 것은 거의 확실히 실수라고 했다(#2). FranzBusch 도 KeithBauerANZ 의 의견에 동의했다(#12). Jon_Shier 는 @discardableResult 가 Task 를 타고 흐르지 못하면 불편하겠다고 했고, warning 을 error 로 올려 쓰는 곳에서는 source compatible 하지 않으니 upcoming feature 로 가야 하는지를 물었다(#3). ktoso 는 warnings-as-errors 는 쓰는 쪽이 스스로 고른 설정이고, 점진적으로 warning 을 더하는 것은 source breaking 이 아니라고 답했다. 그렇지 않았다면 Swift concurrency 는 단계적으로 들어올 수 없었다는 것이다(#4).

fire-and-forget 이라는 현실 (2026-02-13 부터 02-16)

ktoso 는 큰 코드베이스를 조사한 결과를 올렸다(#5). Button { Task { ... } } 가 흔하고, fire-and-forget 의 경계를 긋기 어렵다는 이야기였다. Andropov 는 앞서 본 센 결과와 함께, 진단에 오류를 놓칠 수 있다는 설명을 더하자고 했다(#6). ktoso 는 note 를 더하는 것은 쉬운 일이라고 답했다(#7).

FlorianPircher 는 Task { set.insert(4) } 가 Task<(inserted: Bool, memberAfterInsert: Int), Never> 가 된다는 점을 들어, Success 가 Void 가 아닌 것을 사람이 알아채기 어려운 경우가 있다고 했다(#14). KeithBauerANZ 는 그 경우에도 _ = set.insert(4) 를 쓰라는 warning 은 좋다고 답했다. 그것은 암묵적 반환의 약점이지 값을 읽지 않는 warning 의 약점이 아니라는 이유다(#21). ktoso 는 Task { } 에 _ = 가 없는 것은 모두 버그라는 일반화에 동의하지 않는다고 했다. 이미 warning 에 지친 개발자들에게 churn 이 얼마나 클지가 걱정이고, 결국 LSG 논의에서 정해질 일이라고 했다(#22, 2026-02-16).

tera 는 오류를 삼키는 코드가 왜 허용되느냐고 물었고(#16), ksluder 는 await task.value 에서 오류가 다시 던져지니 try 가 필요하지만 task 를 저장하지 않으면 그 await 가 아예 없어서 문제라고 설명했다(#17). tera 는 task 가 해제될 때 값을 읽지 않았으면 runtime 에서 걸리는 장치를 제안했고(#18), j-f1 은 Xcode 의 purple runtime issue 로 보여 주는 방법을 이야기했다(#20). tera 스스로 이것은 Thread Sanitizer 같은 진단 도구 쪽 일이고 이 pitch 의 범위 밖이라고 했다(#27, 02-18).

warning 으로 바뀌는 길 (2026-02-16 부터 02-24)

jamieQ 는 새 warning 이 기본 “no usage” 진단 대신 쓰이거나 diagnostic group 에 속해야 -warnings-as-errors 를 쓰는 팀이 따로 제어할 수 있다고 했다(#25, 02-16). 컴파일러의 규칙도 새 warning 은 group 에 속하라고 한다는 것이다. ktoso 는 이튿날 task initializer 전용 warning 메시지를 다듬어 보겠다고 했고(#26, 02-17), 2월 24일에는 warning 메시지를 다시 쓰고 문서와 예제가 달린 warning group 을 더했으며 제안서를 고쳤다고 알렸다(#28). 앞에서 본 [#NoUseUnstructuredThrowingTask] 가 그 group 이다. 전용 warning 으로의 전환은 최종 제안서의 “Previous iterations” 단락에 적혀 있다. 이전 판은 overload 를 나눠 Failure 가 Never 인 판에서만 attribute 를 남겼는데, 그러면 typed throws 를 도입해 줄이려던 overload 를 다시 늘리게 되므로 새 warning 으로 바꾼다는 설명이다.

리뷰 (2026-03-16 부터 03-30)

hborla 가 리뷰를 열었다(#1, 2026-03-16). CrystDragon 은 +1 이면서도 컴파일러를 복잡하게 하는 “bespoke warning mechanism” 이 일반적으로는 선호되지 않는 것 아니냐고 물었다(#2, 03-17). ktoso 는 일반 기능으로 모델링하는 쪽이 낫다는 데 동의하고, 구현은 앞에서 본 attribute 방식이며 나중에 정식 attribute 로 일반화할 수 있다고 했다. 6.4 일정에 이미 늦었으니 그것은 독립된 리뷰로 하자고 했다(#3).

jrose 는 typed throws 이전의 overload 로 이 일을 할 수 없느냐고 물었다(#5, 03-18). ktoso 는 목표 하나가 overload 수를 줄이는 것이라고 답했다. task initializer 와 task group 의 overload 가 너무 많아서 gyb 로 생성해야 했고, typed throws 로 gyb 를 없애는 작업이 따로 진행 중이라는 설명이다(#6). OneSadCookie 는 task handle 을 버리는 것이 대체로 바람직하지 않다고 믿는다면서도 현 상태보다 낫다며 +1 을 했다(#7).

ellie20 는 나중에 정식 spelling 이 생긴다면 @discardableResult(where Failure == Never) 같은 where 절이 어떠냐고 했다. 그리고 새 compiler 내부 규칙이 Void 가 아니거나 @discardableResult 가 아닌 closure 까지 다루도록 확장하는 것도 고려해 볼 만하다고 했다(#8, 03-25). tera 는 Success == Void 까지 붙여 오류뿐 아니라 결과도 잃지 않게 하자고 했다(#9). tera 가 mock 으로 시도한 결과를 올리자(#12, 03-30), pyrtsa 는 Task<Void, Never> 만 @discardableResult 로 두는 것이 가장 분명하다고 동의하면서도, continuation.yield(42) 를 단일 표현식으로 담는 task 가 Task<YieldResult, Never> 가 되어 _ = 를 강요받는 경우를 들어 실용상 churn 이 클 수 있다고 했다(#13, #15).

이 리뷰의 끝에 ktoso 는 현실적인 소식을 전했다. typed throws 를 이 API 들에 적용하자 source compatibility 회귀가 쏟아져서 되돌렸고(PR #88172), 이 API 들이 typed throws 를 채택하려면 그 영향부터 풀어야 한다는 것이다. 논의는 throws 만 놓고 이어 가되 제안의 취지는 그대로라고 했다(#17, 2026-03-30). 앞에서 본 Task<(), any Error> 가 그 결과다.

수락 (2026-04-21)

hborla 는 수락 공지(#1)에서 리뷰가 긍정적이었고, 논의는 버려지는 task handle 에 warning 을 더 낼 경우에 몰렸다고 정리했다. 한 가지는 받지 않았고 한 가지는 별개 문제로 미뤘다. 첫째, 버려지는 모든 task handle 에 warning 을 내자는 의견은 너무 광범위하다고 보았다. fire-and-forget 은 흔하고 의도적인 패턴이어서 _ = 를 강요하면 소음만 늘고 얻는 것이 없다는 이유다. 둘째, 결과를 내는 task 를 버릴 때 warning 을 내자는 의견은 개선할 가치가 있다고 보면서도 처리되지 않은 오류와는 별개의 문제로 보았다. 특히 @discardableResult 가 closure 의 결과를 통해 전파되는 경우는 별도 설계 논의가 필요하다고 했다. 같은 날 hborla 는 리뷰 스레드에도 수락 소식을 남겼다(#18).


기대 효과

  • 오류를 던지는 task 를 버리면 컴파일러가 알려 준다. 앞의 Swallow.swift 의 첫 task 가 그런 모양이었다.
  • 진단이 API 이름과 해결 방법(note)을 함께 알려 준다. Task.detached, immediate, immediateDetached, executorPreference: 판이 모두 같은 group 에 묶여 한 번에 제어된다.
  • 의도적으로 버리려면 _ = 한 줄이면 되고, 그 한 줄이 코드를 읽는 사람에게 “오류를 일부러 놓는다” 는 신호가 된다.
  • 진단이 group 에 속해서 팀이 -Werror, -Wwarning, -suppress-warnings 로 마이그레이션 속도를 고를 수 있다.
  • attribute 와 overload 구조를 건드리지 않고 컴파일러 진단만 더하니, 나중에 정식 attribute 로 일반화할 길도 열려 있다.

다른 선택지는 왜 안 됐나

아무것도 하지 않기

제안서는 이 문제가 오랫동안 제기되었으니 개선해야 한다고 본다. 앞의 Swallow.swift 에서 보듯 지금 상태에서 오류는 어떤 진단도 없이 사라진다.

overload 를 나눠 attribute 를 떼기

pitch 의 첫 모양이다. 이 안을 모방해서 MockTask 에 Failure == Never 판에는 @discardableResult 를 두고 Failure == any Error 판에서는 뺐다.

Mock.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// pitch 때 안: Failure == any Error 판에서 @discardableResult 를 뺀 overload 쌍
struct MockTask<Success, Failure: Error> {}

extension MockTask where Failure == Never {
  @discardableResult
  init(operation: () -> Success) {}
}

extension MockTask where Failure == any Error {
  init(operation: () throws -> Success) {}
}

struct Boom: Error {}
func boom() throws { throw Boom() }

func cases() {
  MockTask { print("plain") }
  MockTask { try boom() }
  MockTask { 42 }
  _ = MockTask { try boom() }
}
1
2
3
4
5
6
7
8
9
10
Mock.swift:18:3: warning: result of 'MockTask<Success, Failure>' initializer is unused [#NoUsage]
16 | func cases() {
17 |   MockTask { print("plain") }
18 |   MockTask { try boom() }
   |   `- warning: result of 'MockTask<Success, Failure>' initializer is unused [#NoUsage]
19 |   MockTask { 42 }
20 |   _ = MockTask { try boom() }

[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>
[exit 0]

던지는 18번 줄에 warning 이 나지만 문장은 기본 result of 'MockTask<Success, Failure>' initializer is unused [#NoUsage] 이고 오류를 놓칠 수 있다는 설명이 없다. 던지지 않는 17번과 19번은 조용하고 _ = 는 조용하다. 동작은 의도대로지만, Andropov 가 바랐던 설명(#6)이 없고 [#NoUsage] 가 이 일을 위한 group 이 아니라서 따로 제어할 수 없다. jamieQ 가 짚은 지점이다(#25). 제안서는 이 방식이 typed throws 로 overload 수를 줄이려던 계획과 맞지 않는다고 적고, ktoso 도 리뷰에서 같은 방향을 말했다(#6). 6.4 interface 에는 이미 Never 판과 any Error 판 두 개가 있으니 선언 수보다는, 앞에서 측정한 note 없는 [#NoUsage] 문장과 별도 group 이 없다는 점이 이 안의 약점이다.

던지지 않는 initializer 까지 attribute 빼기

제안서는 던지지 않는 task 는 값을 돌려주든 Void 든 대개 의도적인 fire-and-forget 이라고 본다. 그럴 때 결과를 쓰고 싶다면 task 를 저장하거나 바로 await 했을 것이라는 이유다. 그래서 던지지 않는 initializer 의 attribute 는 그대로 둔다. 앞의 NonVoid.swift 가 그 결과다. KeithBauerANZ, FranzBusch, pyrtsa 는 Task<Void, Never> 만 남기자는 쪽이었다. pyrtsa 도 continuation.yield 의 경우 _ = 가 강요되는 churn 이 있다고 인정했다(#15). ktoso 는 churn 을 걱정했다(#22). 수락 공지도 이 문제를 별개로 보고, 특히 @discardableResult 를 closure 결과로 전파하는 경우는 별도 설계 논의가 필요하다고 했다.

버려지는 모든 task handle 에 warning 내기

수락 공지가 받지 않은 첫째 의견이다. 이 경우 fire-and-forget 이 _ = 투성이가 되고 소음만 는다고 LSG 는 판단했다. Button 의 action 같은 자리에서 Task { ... } 는 지금도 흔하다.


Swift 6 모드와 마이그레이션

새 문법이 없고 진단만 더해지니 소스는 그대로 컴파일된다. 다만 새 warning 이 생기고, 앞에서 본 것처럼 -warnings-as-errors 를 쓰면 error 가 된다. Swift 5 모드는 어떻게 되는지 Warn.swift 로 확인했다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 Warn.swift 2>&1 | grep -oE '^Warn.swift:[0-9]+:[0-9]+: (error|warning)'
1
2
3
4
5
6
Warn.swift:7:3: warning
Warn.swift:8:3: warning
Warn.swift:10:8: warning
Warn.swift:11:8: warning
Warn.swift:12:8: warning
Warn.swift:14:3: warning

Swift 5 모드에서도 같은 여섯 줄에 warning 이 난다. 언어 모드를 올리지 않아도 컴파일러 버전만 6.4 로 올리면 보인다. 제안서의 ABI 절도 컴파일 타임 진단만 바뀌어 ABI 에 영향이 없다고 적는다.

이 진단은 배포 대상 OS 와 상관없이 난다. 컴파일러가 내는 것이라 back-deploy 의 문제가 아니다. 배포 대상을 macOS 14 로 낮춰서 같은 파일을 컴파일했다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Warn.swift 2>&1 | grep -oE '^Warn.swift:[0-9]+:[0-9]+: (error|warning)'
1
2
3
4
5
6
7
8
Warn.swift:7:3: warning
Warn.swift:8:3: warning
Warn.swift:10:8: warning
Warn.swift:11:8: error
Warn.swift:11:8: warning
Warn.swift:12:8: error
Warn.swift:12:8: warning
Warn.swift:14:3: warning

warning 은 여섯 줄 모두 그대로 나온다. 11번과 12번에는 error 도 같이 나오는데 immediate 와 immediateDetached 자체가 macOS 26.0 이상이라서다.

1
2
Warn.swift:11:8: error: 'immediate(name:priority:executorPreference:operation:)' is only available in macOS 26.0 or newer
Warn.swift:12:8: error: 'immediateDetached(name:priority:executorPreference:operation:)' is only available in macOS 26.0 or newer

새 warning 을 고치는 길은 앞에서 본 세 가지다. task 안에서 오류를 처리하거나, _ = 로 버리겠다고 적거나, task 를 받아서 value 나 result 로 오류를 확인한다. 이 셋을 한 파일에 모아 warning 이 사라지는지 확인했다.

Fix.swift

1
2
3
4
5
6
7
8
9
10
11
12
struct Boom: Error {}
func boom() throws { throw Boom() }

func fixes() async throws {
  Task { try? boom() }
  Task {
    do { try boom() } catch { print("handled \(error)") }
  }
  _ = Task { try boom() }
  let task = Task { try boom() }
  try await task.value
}
1
[exit 0]

진단이 없다. 처음 두 task 는 오류가 task 안에서 끝나서 Failure 가 Never 가 된다(try? 판은 Task<Optional<()>, Never>, do/catch 판은 Task<(), Never>). 세 번째는 버리겠다는 뜻을 적었고, 네 번째는 try await task.value 로 오류를 호출한 쪽에 올려 보낸다. 어느 길을 고를지는 task 가 던지는 오류를 누가 책임지느냐에 달려 있다. 이 task 의 오류를 정말 아무도 볼 필요가 없다면 _ = 보다는 try? 나 do/catch 로 task 안에서 로그라도 남기는 쪽이 코드에 의도를 더 잘 남긴다.

한꺼번에 많은 warning 이 쏟아지는 프로젝트라면 group 이름으로 제어하는 것이 현실적이다. 팀이 -warnings-as-errors 를 쓴다면 -Wwarning NoUseUnstructuredThrowingTask 로 이 진단만 warning 으로 되돌려 두고, 코드를 고치는 대로 되돌리면 된다.


정리

  • 결과를 받아 두지 않은 throwing unstructured task 를 만들면 [#NoUseUnstructuredThrowingTask] warning 이 난다. 대상은 Task.init, detached, immediate, immediateDetached 와 executorPreference: 판이다.
  • Task { }, Task { 42 }, Task { () throws(Never) in }, _ = Task { try boom() }, let t = Task { ... }, group.addTask 는 조용하다. try? 나 do/catch 로 task 안에서 오류를 처리해도 조용하다.
  • @discardableResult 는 그대로이고 컴파일러 진단이 더해진다. Failure == Never 판과 Failure == any Error 판 두 overload 는 6.4 SDK interface 에서 모두 @discardableResult 다.
  • Task { () throws(Boom) in ... } 의 타입은 Task<(), any Error> 다.
  • 단일 표현식 함수나 () -> Void closure 안의 Task { try boom() } 도 warning 이다. closure 가 task 를 반환하는 타입이면 조용하다.
  • diagnostic group 에 속해서 -Werror, -Wwarning, -suppress-warnings 로 제어된다. Swift 5 모드에서도, 낮은 배포 대상에서도 같은 진단이 난다.
  • 버려지는 모든 task 와 값을 돌려주는 task 에 warning 을 내는 것은 이 제안에 들어가지 않았고, 수락 공지는 후자를 별도 설계 문제로 남겼다.

관련 글


참고자료

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