포스트

[SE-0466] Control default actor isolation inference

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


제안서 정보


한 줄 요약

모듈 하나를 통째로 main actor 에 두는 모드가 생겼다. 컴파일러 옵션 -default-isolation MainActor (SwiftPM 에서는 .defaultIsolation(MainActor.self)) 를 주면, isolation 을 따로 적지 않은 선언이 nonisolated 대신 @MainActor 로 추론된다. 단일 스레드로 짠 앱 코드가 data-race 오류를 내는 일을 줄이려는 모드이고, 기본값은 지금까지와 같은 nonisolated 다. 이 글은 어떤 선언에 @MainActor 가 붙고 어떤 선언은 그대로 남는지를, 컴파일러에 직접 물어서 정리한다.


어떤 문제였나

SE-0466 은 새 문법이 아니라 새 기본값이다. 그래서 먼저 “기본값이 왜 문제였는가” 부터 본다. Swift 6 언어 모드에서 isolation 을 적지 않은 코드는 nonisolated 다. 이 기본값은 동시성을 쓰는 코드에는 맞지만, 동시성을 쓰지 않는 코드에는 오류를 만든다.

이 글의 뼈대는 이렇다. 문제를 두 가지로 나눠서 컴파일러 진단으로 보고, 바뀌는 것을 모듈 단위 설정, 추론 규칙, init 과 deinit, 클로저, nonisolated 로 빠져나가는 법, 프로토콜 conformance, Sendable 을 물려받는 프로토콜, override 순서로 측정한다. 그다음 포럼 스레드 여섯 개를 따라가고, 소스 호환과 마이그레이션을 본다.

앞 글들의 내용은 짧게 짚고 간다.

  • SE-0449 글: nonisolated 를 타입과 extension 에 붙여서 global actor 추론을 막는 문법. 이 글의 nonisolated 로 빠져나가기가 이 문법이다
  • SE-0412 글: 전역 변수와 static 변수가 Sendable 이거나 global actor 에 묶여야 한다는 규칙
  • SE-0434 글: global actor 에 묶인 타입을 쓰기 쉽게 만든 변경
  • SE-0461 글: nonisolated async 함수가 어디서 도는지를 정한 제안. 이 글의 where 실험에서 같이 켠다

main actor 에서 도는 앱 코드

앱을 만들 때 코드의 대부분은 main actor 에서 돈다. SwiftUI 의 View, UIKit 의 UIViewController 같은 UI 타입이 이미 @MainActor 이고, 이 타입을 쓰는 코드도 같이 main actor 로 끌려 들어가기 때문이다. 동시성을 일부러 쓴 적이 없는 코드가 @MainActor 와 nonisolated 의 경계를 만나면, 그때부터 isolation 이라는 개념을 알아야 한다. 제안서 Motivation 은 이 상황을 “main actor 위에서만 도는 코드가 false positive 오류를 낸다” 고 묶고 다섯 가지 예를 든다. 전역과 static 변수, nonisolated 프로토콜을 채택한 main actor 타입의 conformance, 클래스의 deinit, nonisolated 슈퍼클래스 메서드의 override, SDK 의 main actor API 호출이다. 이 글의 실험은 이 다섯 가지를 모두 포함한다.

이 글의 진단 명령

이 글의 진단은 모두 -emit-sil 로 뽑았다. -emit-sil 은 타입 검사 뒤 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계의 진단까지 낸다. 타입 검사까지만 하는 -typecheck 는 SIL 단계의 진단(초기화 검사, region 검사)을 빼먹는다. 아래 명령에서 -o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 최상위 코드가 없는 일반 소스 파일로 다루라는 옵션이며, -wmo 는 모든 파일을 한 모듈로 같이 컴파일하게 한다. 이 옵션들의 자세한 이야기는 SE-0423 글에 있다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Motivation.swift

main actor 모드로 컴파일하는 판은 같은 명령에 -default-isolation MainActor 만 더한다. 이 글에서 “기본” 이라고 하면 Swift 6 언어 모드에 아무 옵션도 더하지 않은 판이고, “MainActor 모드” 라고 하면 이 옵션을 더한 판이다. 컴파일러는 Apple Swift version 6.4 (swiftlang-6.4.0.34.1) 이다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -default-isolation MainActor Motivation.swift

첫 번째 예는 전역 변수와 static 변수다. 최상위 코드가 없는 파일에서, 이름 그대로 읽으면 아무 문제가 없어 보이는 코드다.

Motivation.swift

1
2
3
4
5
6
7
8
9
10
var counter = 0

struct Settings {
  static var theme = "light"
}

func bump() {
  counter += 1
  Settings.theme = "dark"
}

counter 는 전역 변수이고 Settings.theme 은 static 변수다. bump() 는 이 둘을 고치기만 한다. 스레드를 만든 적도 없고 Task 를 쓴 적도 없다. 기본 Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Motivation.swift:1:5: error: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
 1 | var counter = 0
   |     |- error: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
   |     |- note: convert 'counter' to a 'let' constant to make 'Sendable' shared state immutable
   |     |- note: add '@MainActor' to make var 'counter' part of global actor 'MainActor'
   |     `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
 2 | 
 3 | struct Settings {

Motivation.swift:4:14: error: static property 'theme' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
 2 | 
 3 | struct Settings {
 4 |   static var theme = "light"
   |              |- error: static property 'theme' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
   |              |- note: convert 'theme' to a 'let' constant to make 'Sendable' shared state immutable
   |              |- note: add '@MainActor' to make static property 'theme' part of global actor 'MainActor'
   |              `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
 5 | }
 6 | 

[#MutableGlobalVariable]: <https://docs.swift.org/compiler/documentation/diagnostics/mutable-global-variable>
[exit 1]

두 변수 모두 “nonisolated 전역 공유 가변 상태라서 concurrency-safe 가 아니다” 라는 오류다. 컴파일러가 제안하는 길은 세 개다. let 으로 바꿔서 불변으로 만들거나, @MainActor 를 붙여서 main actor 에 넣거나, 외부 동기화로 지킨다고 약속하고 검사를 끈다. 동시성을 쓴 적이 없는 코드에게 이 세 길은 모두 낯설다. 가운데 길인 @MainActor 가 현실적인데, 문제는 이 속성이 전파된다는 점이다. bump() 가 counter 를 고치려면 bump() 도 main actor 에 있어야 하고, bump() 를 부르는 함수도 그래야 한다.

같은 코드를 MainActor 모드로 컴파일하면 오류가 없다.

1
[exit 0]

counter, Settings.theme, bump() 가 모두 @MainActor 로 추론되어서, 서로 같은 isolation 이니 전파할 것이 없다. 코드는 한 글자도 바꾸지 않았다.

SE-0412 의 규칙은 언어 모드에 따라 오류의 강도가 다르다. 같은 파일을 세 모드로 컴파일한 결과다.

1
2
3
4
5
6
7
=== Motivation.swift [-swift-version 5]
=== Motivation.swift [-swift-version 5 -strict-concurrency=complete]
Motivation.swift:1:5: warning: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state; this is an error in the Swift 6 language mode [#MutableGlobalVariable]
Motivation.swift:4:14: warning: static property 'theme' is not concurrency-safe because it is nonisolated global shared mutable state; this is an error in the Swift 6 language mode [#MutableGlobalVariable]
=== Motivation.swift [-swift-version 6]
Motivation.swift:1:5: error: var 'counter' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
Motivation.swift:4:14: error: static property 'theme' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]

Swift 5 모드는 아무 말도 하지 않고, -strict-concurrency=complete 를 주면 경고를 내며 그 경고가 “Swift 6 언어 모드에서는 오류” 라고 알려 준다. Swift 6 모드에서 오류가 된다. SE-0466 이 겨냥하는 쪽은 이 마지막 모드다. 동시성을 쓰지 않는 단일 스레드 코드가 Swift 6 의 완전한 검사를 거쳐야 할 때의 비용을 줄이려는 것이다.


@MainActor 를 적어도 남는 오류

@MainActor 를 손으로 붙이는 방법은 어떨까. 앞의 첫 번째 예는 붙이면 풀리지만, 두 번째 예는 붙여도 풀리지 않는다. nonisolated 프로토콜을 채택한 main actor 타입이다.

Conformance.swift

1
2
3
4
5
6
7
8
9
protocol Describable {
  func describe() -> String
}

@MainActor
final class Counter: Describable {
  var count = 0
  func describe() -> String { "count = \(count)" }
}

Describable 은 아무것도 붙이지 않은 프로토콜이고, Counter 는 @MainActor 클래스다. Counter.describe() 는 클래스를 따라 @MainActor 이므로, nonisolated 요구사항을 만족시킬 수 없다. 기본 Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Conformance.swift:6:22: error: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
 4 | 
 5 | @MainActor
 6 | final class Counter: Describable {
   |                      |- error: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
   |                      |- note: isolate this conformance to the main actor with '@MainActor'
   |                      `- note: turn data races into runtime errors with '@preconcurrency'
 7 |   var count = 0
 8 |   func describe() -> String { "count = \(count)" }
   |        |- note: main actor-isolated instance method 'describe()' cannot satisfy nonisolated requirement
   |        `- note: mark instance method 'describe()' 'nonisolated'
 9 | }
10 | 

[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]

오류의 문장은 “Counter 의 Describable conformance 가 main actor 격리 코드로 넘어가서 data race 가 날 수 있다” 이고, 노트가 고칠 길을 둘 준다. @MainActor 로 conformance 자체를 main actor 에 가두거나(SE-0470 의 isolated conformance), @preconcurrency 로 검사를 런타임으로 미루거나, 메서드를 nonisolated 로 만드는 길이다. 앞의 둘은 새 개념이 둘 더 필요하고, 마지막은 메서드 본문이 count 를 읽을 수 없게 만든다.

코드에 나온 것

SE-0470 은 isolated conformance 를 정한 제안이다. @MainActor 가 붙은 타입이 nonisolated 프로토콜을 채택하면서 “이 conformance 는 main actor 안에서만 쓸 수 있다” 고 선언하게 한다. 자세한 규칙은 SE-0470 글에서 다룬다. 이 conformance 를 자동으로 @MainActor 에 두는 upcoming feature 가 InferIsolatedConformances 다.

MainActor 모드로 컴파일하면 이 오류도 사라진다.

1
[exit 0]

프로토콜 Describable 도 @MainActor 로 추론되어서(프로토콜은 뒤에서 본다), 요구사항과 구현이 같은 isolation 이 된다. 오류가 사라진 이유가 “검사를 껐다” 가 아니라 “양쪽이 같은 isolation 이 되었다” 라는 점이 중요하다. 이 글에서는 이 차이를 계속 따라간다. InferIsolatedConformances 만 켠 판도 위 코드에서는 오류가 없다.

1
[exit 0]

이 feature 는 @MainActor 타입의 conformance 를 자동으로 isolated conformance 로 만들어서 같은 코드를 통과시킨다. 이 두 길은 효과가 같아 보이지만, 모듈 전체에 무슨 일이 생기는지는 다르다. 뒤의 “프로토콜과 conformance” 절에서 isolated conformance 를 nonisolated 문맥에서 쓰면 어떤 오류가 나는지 본다.


무엇이 바뀌나

SE-0466 이 더하는 것은 두 가지다. 컴파일러 옵션 -default-isolation 과, 같은 일을 하는 SwiftPM 설정 defaultIsolation 이다. 이 위에 “isolation 을 적지 않은 선언” 이 어떻게 추론되는지의 규칙이 따른다.


모듈 단위 기본 isolation

옵션은 두 값만 받는다. 기본값은 nonisolated 이고 선택지는 MainActor 다.

Flag.swift

1
func f() {}

먼저 MainActor 를 주었을 때다. 선언의 isolation 은 -print-ast 로 찍어서 본다.

1
xcrun swiftc -print-ast -swift-version 6 -default-isolation MainActor Flag.swift
1
2
@MainActor internal func f() {
}

f() 에 @MainActor 가 붙었다. 값에 = 를 써서 -default-isolation=MainActor 로 주어도 같다.

1
2
@MainActor internal func f() {
}

같은 옵션으로 엉뚱한 값을 주면 컴파일러가 거부한다.

1
2
<unknown>:0: error: invalid value 'MyActor' in '-default-isolation MyActor'
[exit 1]
1
2
<unknown>:0: error: invalid value 'mainactor' in '-default-isolation mainactor'
[exit 1]

사용자 정의 global actor 를 쓰는 길은 없고, 대소문자도 구분한다. 값은 MainActor 와 nonisolated 둘뿐이다. 값 둘을 모두 주면 어떻게 되는지도 확인했다. 오류는 없고 뒤에 준 값이 이긴다. MainActor 를 먼저, nonisolated 를 나중에 주면 f() 에 아무것도 안 붙는다.

1
xcrun swiftc -print-ast -swift-version 6 -default-isolation MainActor -default-isolation nonisolated Flag.swift
1
2
internal func f() {
}

순서를 바꿔서 nonisolated 를 먼저, MainActor 를 나중에 주면 @MainActor 가 붙는다.

1
xcrun swiftc -print-ast -swift-version 6 -default-isolation nonisolated -default-isolation MainActor Flag.swift
1
2
@MainActor internal func f() {
}

SwiftPM 에서는 타깃 단위로 설정한다. tools version 6.2 부터 쓸 수 있는 SwiftSetting.defaultIsolation 이고, 값은 MainActor.self 와 nil 둘이다. 라이브러리 타깃과 실행 타깃이 나뉜 패키지를 만들었다. 라이브러리 타깃 Core 는 설정이 없고, 실행 타깃 App 만 MainActor 로 둔다.

Package.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// swift-tools-version: 6.2
import PackageDescription

let package = Package(
  name: "Pkg",
  platforms: [.macOS(.v15)],
  targets: [
    .target(name: "Core"),
    .executableTarget(
      name: "App",
      dependencies: ["Core"],
      swiftSettings: [.defaultIsolation(MainActor.self)]
    ),
  ]
)

Core 는 일부러 아무 설정도 하지 않은 타깃이다.

Sources/Core/Core.swift

1
2
3
4
5
6
7
8
public func checksum(_ bytes: [UInt8]) -> Int {
  bytes.reduce(0) { $0 &+ Int($1) }
}

public final class Cache {
  public var items: [String] = []
  public init() {}
}

App 의 두 파일이다. 전역 변수 theme 은 @MainActor 가 필요한 선언이다.

Sources/App/Settings.swift

1
2
3
4
5
var theme = "light"

func localChecksum(_ bytes: [UInt8]) -> Int {
  bytes.reduce(0) { $0 &+ Int($1) }
}

Sources/App/main.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
import Core

theme = "dark"

@concurrent func work() async -> Int {
  checksum([1, 2, 3])
}

@concurrent func localWork() async -> Int {
  await localChecksum([1, 2, 3])
}

print(theme, await work(), await localWork())

work() 와 localWork() 는 @concurrent 로 main actor 밖에서 돌게 했다. localWork() 는 await 가 필요한데, localChecksum 이 App 모듈 안에서 main actor 로 추론되어서 main actor 밖에서 부르는 호출이 되기 때문이다. 빌드하고 실행한 결과다.

1
2
swift build
swift run App
1
2
Build complete!
dark 6 6

swift build -v 로 컴파일러 호출을 보면 -default-isolation MainActor 가 -module-name App 호출에만 붙고 Core 에는 붙지 않는다. 설정은 그 타깃 하나에만 적용된다는 뜻이다. Core.swift 끝에 전역 변수 한 줄을 더해서 확인했다.

1
public var hits = 0

Core 는 기본값이 nonisolated 라서 Swift 6 의 전역 변수 규칙이 그대로 걸린다. App 의 theme 은 같은 모양인데 통과했다.

1
2
3
4
5
6
7
8
9
10
11
Sources/Core/Core.swift:9:12: error: var 'hits' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
 7 |   public init() {}
 8 | }
 9 | public var hits = 0
   |            |- error: var 'hits' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
   |            |- note: convert 'hits' to a 'let' constant to make 'Sendable' shared state immutable
   |            |- note: add '@MainActor' to make var 'hits' part of global actor 'MainActor'
   |            `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
10 |

[#MutableGlobalVariable]: <https://docs.swift.org/compiler/documentation/diagnostics/mutable-global-variable>

이 절의 포인트는 “모듈” 이다. 한 타깃에 설정을 주면 그 타깃의 모든 소스 파일이 같은 모드가 되고, 다른 타깃이나 의존하는 라이브러리는 영향을 받지 않는다. 포럼에서 파일 단위 설정을 바란 사람이 여럿 있었는데, 제안서는 이것을 Future direction 으로 남기고 CompilerSettings pitch 를 연결한다.

nil 은 기본값 nonisolated 를 명시하는 값이다. .defaultIsolation(nil) 로 바꾸고 빌드하면 컴파일러에 -default-isolation nonisolated 가 전달되고, theme 의 오류가 되살아난다.

1
2
3
4
5
6
7
Sources/App/Settings.swift:1:5: error: var 'theme' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
1 | var theme = "light"
  |     |- error: var 'theme' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
  |     |- note: convert 'theme' to a 'let' constant to make 'Sendable' shared state immutable
  |     |- note: add '@MainActor' to make var 'theme' part of global actor 'MainActor'
  |     `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
2 |

이 API 는 tools version 이 6.2 보다 낮으면 쓸 수 없다. // swift-tools-version: 6.1 로 내렸을 때의 오류다.

1
2
3
4
5
6
7
8
9
Package.swift:12:24: error: 'defaultIsolation' is unavailable
10 |       name: "App",
11 |       dependencies: ["Core"],
12 |       swiftSettings: [.defaultIsolation(MainActor.self)]
   |                        `- error: 'defaultIsolation' is unavailable
13 |     ),
14 |   ]

PackageDescription.SwiftSetting.defaultIsolation:3:22: note: 'defaultIsolation' was introduced in PackageDescription 6.2

Xcode 에서는 build setting SWIFT_DEFAULT_ACTOR_ISOLATION (표시 이름 “Default Actor Isolation”) 이 같은 일을 한다. Xcode 27 의 Swift.xcspec 에서 이 설정은 nonisolated 와 MainActor 중에서 고르는 값이고, 기본값은 nonisolated, MainActor 를 고르면 컴파일러에 -default-isolation=MainActor 를 전달한다. 설명문은 이 설정이 순차 코드에서 나는 data-race 안전 오류의 false positive 를 줄이려는 것이라고 적는다. 새 앱 프로젝트 템플릿(App Base.xctemplate)은 이 값을 MainActor 로 켜 놓고, 프로젝트 기본 설정 템플릿(Base_ProjectSettings.xctemplate)은 SWIFT_VERSION = 5.0 과 SWIFT_APPROACHABLE_CONCURRENCY = YES 를 같이 둔다. SWIFT_APPROACHABLE_CONCURRENCY 는 DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances, InferSendableFromCaptures, NonisolatedNonsendingByDefault 다섯 feature 를 한꺼번에 켜는 설정이다. 새 프로젝트가 이 설정을 켠 채로 나온다는 사실이 뒤의 스레드 절에서 다시 나온다.

언어 모드와의 관계도 짚어 둔다. -default-isolation MainActor 는 Swift 5 모드에서도 쓸 수 있다. Swift 5 모드에서 추론된 선언은 @preconcurrency 가 같이 붙는다.

1
2
@MainActor @preconcurrency internal func f() {
}

(ast.sh 는 -swift-version 6 을 먼저 주는데, 뒤에 준 -swift-version 5 가 이긴다.)


추론 규칙

MainActor 모드에서 무엇에 @MainActor 가 붙는지가 이 제안의 가장 큰 부분이다. 제안서는 규칙을 “isolation 을 적지 않은 선언에 @MainActor 를 추론한다” 로 시작해서, 예외를 하나씩 단다. 규칙부터 그림으로 보고, 하나씩 측정한다.

-default-isolation MainActor 에서 철자 없는 선언이 가는 곳을 보인 그림이다. 전역 함수와 변수, 타입과 멤버, static 속성, 직접 쓴 init, 서브클래스가 물려받는 init, deinit 을 안 쓴 클래스의 deinit, @Sendable 이 아닌 클로저, 프로토콜은 @MainActor 가 되고, actor 안쪽, 명시한 isolation, 부모 선언이나 프로토콜에서 물려받은 global actor, nonisolated 타입 안의 중첩 타입, SendableMetatype 프로토콜을 직접 채택한 타입, memberwise init 과 부모 없는 클래스의 합성 init, 직접 쓴 deinit, typealias 와 import 와 enum case 와 접근자처럼 global actor 를 가질 수 없는 선언은 기본값을 받지 않는다

왼쪽 칸이 @MainActor 가 붙는 선언이고 오른쪽 점선 칸이 기본값을 받지 않는 선언이다. 제안서가 이 규칙을 보이려고 쓴 예제 코드를 컴파일해서 컴파일러의 판단을 -print-ast 로 찍었다.

ProposalExample.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
func f() {}

class C {
  init() {}

  deinit {}

  struct Nested {
    func g() {}
  }

  static var value = 10
}

@globalActor
actor MyActor {
  init() {}

  deinit {}

  static let shared = MyActor()
}

@MyActor
protocol P {}

struct S: P {
  func f() {}
}

nonisolated protocol Q: Sendable {}

struct S2: Q {
  struct Inner {
    func g() {}
  }

  struct IsolatedInner: P {
    func g() {}
  }
}

struct S3 {
  func h() {}
}

extension S3: Q {}

이 코드는 규칙 여러 개를 한 파일에 모았다. C 는 일반 클래스, MyActor 는 사용자 정의 global actor, P 는 그 global actor 에 묶인 프로토콜, Q 는 nonisolated 와 Sendable 을 가진 프로토콜이다. MainActor 모드에서 컴파일러가 판단한 결과다.

1
xcrun swiftc -print-ast -swift-version 6 -default-isolation MainActor ProposalExample.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@MainActor internal func f() {
}

@MainActor internal class C {
  @MainActor internal init() {

  }
  @objc deinit {
  }
  @MainActor internal struct Nested {
    @MainActor internal func g() {
    }
    nonisolated internal init() {

    }
  }
  @MainActor @_hasInitialValue internal static var value: Int = 10
}

@globalActor internal actor MyActor {
  internal init() {

  }
  @objc deinit {
  }
  @_hasInitialValue internal static let shared: MyActor = MyActor()
  internal typealias ActorType = MyActor
  @_semantics("defaultActor") nonisolated final internal var unownedExecutor: UnownedSerialExecutor {
    get {
      return UnownedSerialExecutor(buildDefaultActorExecutorRef(self))
    }
  }
}

@MyActor internal protocol P {
}

@MyActor internal struct S : P {
  @MyActor internal func f() {
  }
  nonisolated internal init() {

  }
}

nonisolated internal protocol Q : Sendable {
}

internal struct S2 : Q {
  internal struct Inner {
    internal func g() {
    }
    internal init() {

    }
  }
  @MyActor internal struct IsolatedInner : P {
    @MyActor internal func g() {
    }
    nonisolated internal init() {

    }
  }
  internal init() {

  }
}

@MainActor internal struct S3 {
  @MainActor internal func h() {
  }
  nonisolated internal init() {

  }
}

extension S3 : Q {
}

진단은 [exit 0] 로 깨끗하다.

1
[exit 0]

위의 출력을 규칙별로 읽는다.

  • f() 와 C 는 @MainActor 다. 철자 없는 전역 함수와 클래스의 기본 규칙이다.
  • C.init() 은 @MainActor 이고, C.value 도 @MainActor 다. 직접 쓴 init 과 static 변수에도 규칙이 적용된다.
  • C.Nested 도 @MainActor 이고 그 안의 g() 도 그렇다. 바깥 타입이 nonisolated 가 아니므로 중첩 타입도 기본 규칙을 받는다. Nested 의 합성 init 은 nonisolated 로 찍힌다.
  • MyActor 는 actor 라서 안쪽에는 기본값이 적용되지 않는다. init, deinit, shared 에 아무 속성도 없다. 제안서의 규칙 “actor 안의 선언은 추론하지 않는다” 다. 메서드와 프로퍼티는 어떻게 되는지 아래에서 따로 본다.
  • P 는 @MyActor 이고, P 를 채택한 S 는 @MyActor 가 되었다. 프로토콜에서 global actor 를 물려받으면 기본값은 쓰이지 않는다. S.f() 도 @MyActor 다.
  • Q 는 nonisolated 프로토콜이다. Q 를 채택한 S2 와 그 안의 Inner 는 아무 속성도 없는 nonisolated 로 남았다. Sendable 을 상속하는 프로토콜을 채택하면 기본값이 꺼진다. 이 규칙이 수정안의 내용이고 뒤의 절에서 따로 본다.
  • S2.IsolatedInner 는 P 를 채택해서 @MyActor 다. 중첩 타입이 nonisolated 타입 안에 있어도 자기가 채택한 프로토콜의 global actor 를 가진다.
  • S3 는 @MainActor 이고 S3.h() 도 그렇다. 본문에서는 Q 를 채택하지 않았기 때문이다. 같은 파일 아래쪽의 extension S3: Q {} 는 S3 의 isolation 을 바꾸지 못하고, 그대로 통과한다.
  • C 의 직접 쓴 deinit 은 nonisolated 다. 같은 클래스의 직접 쓴 init() 은 @MainActor 인데 deinit 은 그렇지 않다. C 의 줄만 SIL 에서 뽑았다.
1
2
3
4
5
6
7
C.__allocating_init()                         global_actor MainActor
C.init()                                      global_actor MainActor
C.deinit                                      nonisolated
C.__deallocating_deinit                       nonisolated
C.Nested.g()                                  global_actor MainActor
C.Nested.init()                               nonisolated
C.value.unsafeMutableAddressor                global_actor MainActor

C.init() 과 C.__allocating_init() 은 global_actor MainActor 이고, C.deinit 과 C.__deallocating_deinit 은 nonisolated 다.

한 가지 눈에 띄는 것은 합성되거나 암시적인 init 이다. Nested, S, S3 의 init() 은 모두 nonisolated 로 찍혔다. 직접 쓴 C.init() 은 @MainActor 인데, 쓰지 않아서 컴파일러가 만든 init 은 nonisolated 다. 이 말은 구조체와 부모 클래스가 없는 클래스에만 해당한다. 서브클래스가 합성하거나 물려받는 init 은 @MainActor 라서, 부모의 nonisolated init 과 충돌한다. 이 충돌은 뒤의 override 절에서 오류로 본다. 쓴 init 과 쓰지 않은 init 의 차이가 클래스에서 어떻게 보이는지는 다음 절에서 SIL 로 본다.

actor 안쪽은 따로 한 번 더 찍었다. ActorMembers.swift 는 프로퍼티, init, 메서드, static 상수를 가진 actor 다.

ActorMembers.swift

1
2
3
4
5
6
actor A {
  var n = 0
  init() {}
  func m() {}
  static let s = 0
}

isolation.sh 출력에서 A 의 n 의 getter, init, m, deinit, s 의 getter 줄만 남겼다.

1
2
3
4
5
A.n.getter                                    actor_instance. name: 'self'
A.init()                                      nonisolated
A.m()                                         actor_instance. name: 'self'
static A.s.getter                             unspecified
A.deinit                                      unspecified

메서드와 프로퍼티는 actor_instance 로 actor 자신에게 격리되고, init 은 nonisolated 이며, deinit 과 static 상수는 isolation 이 정해지지 않은 채(unspecified)로 남는다. 어느 것도 main actor 가 되지 않는다. 그러니 actor 안쪽 선언이 전부 nonisolated 가 되는 것은 아니고, 기본값 @MainActor 가 적용되지 않는다는 말이다.

기본값이 적용되지 않는 선언이 하나 더 있다. 제안서는 typealias, import, enum case, 접근자 하나하나처럼 global actor 를 가질 수 없는 선언을 예외로 든다. 이 선언들은 ProposalExample.swift 에 없어서 DeclKinds.swift 를 따로 만들었다.

DeclKinds.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Foundation

typealias ID = Int

enum Kind {
  case a
  case b
}

struct Box {
  var raw = 0
  var value: Int {
    get { raw }
    set { raw = newValue }
  }
}

MainActor 모드에서 컴파일되고, AST 에서 typealias, enum 의 case, Box 부분만 남겼다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
internal typealias ID = Int
@MainActor internal enum Kind {
  case a
  case b
@MainActor internal struct Box {
  @MainActor @_hasInitialValue internal var raw: Int = 0
  @MainActor internal var value: Int {
    get {
      return self.raw
    }
    set {
      self.raw = newValue
    }
  }
  nonisolated internal init() {

  }
  nonisolated internal init(raw: Int = 0)
}

typealias ID 에는 속성이 없고, enum Kind 는 @MainActor 이지만 case a 와 case b 에는 속성이 없다. 계산 프로퍼티 value 는 @MainActor 인데 get 과 set 접근자에는 따로 붙지 않는다. import 는 선언 자체에 isolation 을 적을 수 없다.

프로토콜 isolation 은 따로 찍어 보았다. Conformance.swift 의 Describable 에서 클래스를 뺀 파일이다.

ProtocolIso.swift

1
2
3
protocol Describable {
  func describe() -> String
}
1
2
3
4
@MainActor internal protocol Describable {
  @MainActor func describe() -> String
}

프로토콜에도 @MainActor 가 붙고, 요구사항 describe() 에도 @MainActor 가 붙는다. 요구사항에 붙는다는 것이 앞에서 conformance 오류가 사라진 이유다.


init 과 deinit

위의 규칙 중 가장 설명이 길어진 곳이 init 과 deinit 이다. 클래스 세 모양을 두고 SIL 에서 각 멤버의 isolation 을 읽었다.

Members.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ImplicitAll {
  var x = 0
}

class ExplicitInit {
  var x = 0
  init() {}
}

class ExplicitDeinit {
  var x = 0
  deinit {}
}

final class FinalImplicit {
  var x = 0
}

struct Value {
  var x = 0
}

ImplicitAll 은 아무것도 쓰지 않은 클래스, ExplicitInit 은 init 만 쓴 클래스, ExplicitDeinit 은 deinit 만 쓴 클래스, FinalImplicit 은 final 이고 아무것도 쓰지 않은 클래스, Value 는 구조체다. -emit-silgen 의 // Isolation: 주석을 모아서 선언별로 정리하는 스크립트(isolation.sh)로 뽑았다.

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
variable initialization expression of ImplicitAll.x global_actor MainActor
ImplicitAll.x.getter                          global_actor MainActor
ImplicitAll.x.setter                          global_actor MainActor
ImplicitAll.x.modify                          global_actor MainActor
ImplicitAll.deinit                            global_actor MainActor
static MainActor.shared.getter                unspecified
ImplicitAll.__isolated_deallocating_deinit    global_actor MainActor
ImplicitAll.__deallocating_deinit             nonisolated
swift_task_deinitOnExecutor                   unspecified
ImplicitAll.__allocating_init()               nonisolated
ImplicitAll.init()                            nonisolated
variable initialization expression of ExplicitInit.x global_actor MainActor
ExplicitInit.x.getter                         global_actor MainActor
ExplicitInit.x.setter                         global_actor MainActor
ExplicitInit.x.modify                         global_actor MainActor
ExplicitInit.__allocating_init()              global_actor MainActor
ExplicitInit.init()                           global_actor MainActor
ExplicitInit.deinit                           global_actor MainActor
ExplicitInit.__isolated_deallocating_deinit   global_actor MainActor
ExplicitInit.__deallocating_deinit            nonisolated
variable initialization expression of ExplicitDeinit.x global_actor MainActor
ExplicitDeinit.x.getter                       global_actor MainActor
ExplicitDeinit.x.setter                       global_actor MainActor
ExplicitDeinit.x.modify                       global_actor MainActor
ExplicitDeinit.deinit                         nonisolated
ExplicitDeinit.__deallocating_deinit          nonisolated
ExplicitDeinit.__allocating_init()            nonisolated
ExplicitDeinit.init()                         nonisolated
variable initialization expression of FinalImplicit.x global_actor MainActor
FinalImplicit.x.getter                        global_actor MainActor
FinalImplicit.x.setter                        global_actor MainActor
FinalImplicit.x.modify                        global_actor MainActor
FinalImplicit.deinit                          global_actor MainActor
FinalImplicit.__isolated_deallocating_deinit  global_actor MainActor
FinalImplicit.__deallocating_deinit           nonisolated
FinalImplicit.__allocating_init()             nonisolated
FinalImplicit.init()                          nonisolated
variable initialization expression of Value.x global_actor MainActor
Value.x.getter                                global_actor MainActor
Value.x.setter                                global_actor MainActor
Value.x.modify                                global_actor MainActor
Value.init()                                  nonisolated
default argument 0 of Value.init(x:)          unspecified
Value.init(x:)                                nonisolated

이 표에서 읽을 것은 세 가지다.

첫째, 저장 프로퍼티 x 와 getter, setter 는 전부 global_actor MainActor 다. 이 부분은 기본 규칙이다.

둘째, init 은 쓴 곳만 MainActor 다. ExplicitInit.init() 은 MainActor 이고, 쓰지 않은 ImplicitAll, ExplicitDeinit, FinalImplicit 의 init() 과 __allocating_init() 은 nonisolated 다. 구조체 Value 의 init() 과 init(x:) 도 nonisolated 다. 이 세 클래스는 모두 부모가 없다. 서브클래스가 합성하는 init 은 @MainActor 가 되는데, 그 오류는 override 절의 OverrideDefault.swift 에서 본다.

셋째, deinit 은 쓴 모양에 따라 갈린다. deinit 을 쓰지 않은 클래스(ImplicitAll, FinalImplicit)는 deinit 이 global_actor MainActor 이고, 컴파일러가 __isolated_deallocating_deinit 을 만들어서 main actor 에서 해제되게 한다. __deallocating_deinit 은 nonisolated 로 남고, 이 두 클래스에만 swift_task_deinitOnExecutor 가 같이 나온다. 이름 그대로 해제를 정해진 executor 로 넘기는 런타임 함수다. deinit 을 직접 쓴 ExplicitDeinit 은 deinit 이 nonisolated 다. init 만 쓴 ExplicitInit 의 deinit 은 쓰지 않았으니 MainActor 다.

이 규칙은 isolated deinit 을 정한 SE-0371 과 얽혀 있다. SE-0371 은 deinit 이 isolated 이려면 isolated deinit 이라고 직접 쓰게 했다. 이 제안은 MainActor 모드에서 deinit 을 쓰지 않은 클래스가 암시적으로 isolated deinit 을 갖게 한다. 런타임에서 isolated deinit 이 어떻게 도는지는 SE-0371 글에서 다룬다.

deinit 모양을 더 좁혀서 두 클래스로 비교했다.

DeinitShapes.swift

1
2
3
4
5
6
7
8
9
10
@MainActor
class Explicit {
  var x = 0
  deinit {}
}

@MainActor
class Implicit {
  var x = 0
}

아래 두 출력은 deinit 관련 줄만 남겼다. 먼저 MainActor 모드다.

1
2
3
4
5
6
Explicit.deinit                               nonisolated
Explicit.__deallocating_deinit                nonisolated
Implicit.deinit                               global_actor MainActor
Implicit.__isolated_deallocating_deinit       global_actor MainActor
Implicit.__deallocating_deinit                nonisolated
swift_task_deinitOnExecutor                   unspecified

두 클래스에는 @MainActor 를 손으로 붙였다. 같은 파일을 -default-isolation 없이 Swift 6 기본 모드로 읽으면 결과가 다르다.

1
2
3
4
Explicit.deinit                               nonisolated
Explicit.__deallocating_deinit                nonisolated
Implicit.deinit                               unspecified
Implicit.__deallocating_deinit                nonisolated

Explicit.deinit 은 두 모드 모두 nonisolated 다. Implicit.deinit 은 기본 모드에서 unspecified 이고, MainActor 모드에서 MainActor 가 되며 __isolated_deallocating_deinit 이 생긴다. 손으로 @MainActor 를 붙인 클래스만으로는 deinit 에 isolation 이 붙지 않고, MainActor 모드가 켜져 있을 때 deinit 을 쓰지 않은 클래스에 isolation 이 붙는다.

이 차이가 의미를 갖는 곳은 deinit 안에서 main actor 함수를 부르는 코드다.

Deinit.swift

1
2
3
4
5
6
7
8
9
@MainActor
func cleanup() {}

final class Resource {
  var name = "r"
  deinit {
    cleanup()
  }
}

cleanup() 은 @MainActor 이고, deinit 이 그것을 부른다. 기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Deinit.swift:7:5: error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | @MainActor
 2 | func cleanup() {}
   |      `- note: calls to global function 'cleanup()' from outside of its actor context are implicitly asynchronous
 3 | 
 4 | final class Resource {
 5 |   var name = "r"
 6 |   deinit {
 7 |     cleanup()
   |     `- error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
 8 |   }
 9 | }

[#ActorIsolatedCall]: <https://docs.swift.org/compiler/documentation/diagnostics/actor-isolated-call>
[exit 1]

deinit 은 nonisolated 라서 main actor 함수를 동기로 부를 수 없다. MainActor 모드에서도 deinit 을 직접 썼기 때문에 같은 오류다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Deinit.swift:7:5: error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | @MainActor
 2 | func cleanup() {}
   |      `- note: calls to global function 'cleanup()' from outside of its actor context are implicitly asynchronous
 3 | 
 4 | final class Resource {
 5 |   var name = "r"
 6 |   deinit {
 7 |     cleanup()
   |     `- error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
 8 |   }
 9 | }

[#ActorIsolatedCall]: <https://docs.swift.org/compiler/documentation/diagnostics/actor-isolated-call>
[exit 1]

cleanup() 에 @MainActor 를 붙이지 않은 판은 두 모드가 갈린다. DeinitCall.swift 는 Deinit.swift 에서 cleanup() 의 속성만 뺀 코드다.

1
[exit 0]

기본 모드에서는 둘 다 nonisolated 라 통과한다. MainActor 모드에서는 cleanup() 이 @MainActor 로 추론되고 deinit 은 직접 썼으니 nonisolated 라서, 같은 오류가 다시 난다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
DeinitCall.swift:6:5: error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
1 | func cleanup() {}
  |      `- note: calls to global function 'cleanup()' from outside of its actor context are implicitly asynchronous
2 | 
3 | final class Resource {
4 |   var name = "r"
5 |   deinit {
6 |     cleanup()
  |     `- error: call to main actor-isolated global function 'cleanup()' in a synchronous nonisolated context [#ActorIsolatedCall]
7 |   }
8 | }

[#ActorIsolatedCall]: <https://docs.swift.org/compiler/documentation/diagnostics/actor-isolated-call>
[exit 1]

여기서 고치는 길이 isolated deinit 이다. DeinitIsolated.swift 는 Resource 의 deinit 을 isolated deinit 으로 바꾼 코드다.

1
2
3
4
5
6
7
8
func cleanup() {}

final class Resource {
  var name = "r"
  isolated deinit {
    cleanup()
  }
}

기본 Swift 6 모드에서 이 코드는 오류다. 클래스가 어느 actor 에도 묶이지 않았기 때문이다.

1
2
3
4
5
6
7
8
DeinitIsolated.swift:5:3: error: deinit is marked isolated, but containing class 'Resource' is not isolated to an actor
3 | final class Resource {
4 |   var name = "r"
5 |   isolated deinit {
  |   `- error: deinit is marked isolated, but containing class 'Resource' is not isolated to an actor
6 |     cleanup()
7 |   }
[exit 1]

MainActor 모드에서는 클래스가 @MainActor 이므로 통과하고, SIL 에 Resource.__isolated_deallocating_deinit 이 생긴다.

1
[exit 0]

정리하면 MainActor 모드의 deinit 은 이렇다. 쓰지 않으면 main actor 에서 돌고, 직접 쓰면 nonisolated 이고, main actor 위에서 돌고 싶으면 isolated deinit 이라고 적는다.

CodingKeys 같은 타입도 짚어 둔다. CodingKeys 에는 @MainActor 가 붙지 않는다. 이유는 뒤의 Sendable 절에서 보는 SendableMetatype 규칙이다. 먼저 결과를 본다. 아래 코드는 CodingKeys 를 손으로 쓴 구조체다.

CodingKeys.swift

1
2
3
4
5
6
7
struct S: Codable {
  var a: Int

  enum CodingKeys: CodingKey {
    case a
  }
}

두 모드 모두 컴파일된다.

1
[exit 0]
1
[exit 0]

MainActor 모드의 AST 는 이렇다.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
@MainActor internal struct S : Codable {
  @MainActor internal var a: Int
  internal enum CodingKeys : CodingKey {
    case a
    internal init?(stringValue: String) {
      switch stringValue {
      case "a":
        self = S.CodingKeys.a
      default:
        return nil
      }
    }
    internal init?(intValue: Int) {
      return nil
    }
    @_semantics("derived_enum_equals") @_implements(Equatable, ==(_:_:)) internal static func __derived_enum_equals(_ a: S.CodingKeys, _ b: S.CodingKeys) -> Bool {
      var index_a: Int
      switch a {
      case .a:
        index_a = 0
      }
      var index_b: Int
      switch b {
      case .a:
        index_b = 0
      }
      return index_a == index_b
    }
    internal func hash(into hasher: inout Hasher) {
      var discriminator: Int
      switch self {
      case .a:
        discriminator = 0
      }
      hasher.combine(discriminator)
    }
    internal var hashValue: Int {
      get {
        return _hashValue(for: self)
      }
    }
    internal var intValue: Int? {
      get {
        return nil
      }
    }
    internal var stringValue: String {
      get {
        switch self {
        case .a:
          return "a"
        }
      }
    }
  }
  @MainActor internal func encode(to encoder: any Encoder) throws {
    var container = encoder.container(keyedBy: S.CodingKeys.self)

    try container.encode(self.a, forKey: S.CodingKeys.a)
  }
  nonisolated internal init(a: Int)
  @MainActor internal init(from decoder: any Decoder) throws {
    @_hasInitialValue let container: KeyedDecodingContainer<S.CodingKeys> = try decoder.container(keyedBy: S.CodingKeys.self)

    self.a = try container.decode(Int.self, forKey: S.CodingKeys.a)

  }
}

S 와 프로퍼티 a 는 @MainActor 이고, CodingKeys 열거형에는 속성이 없다. 합성된 encode(to:) 와 init(from:) 은 @MainActor 다. memberwise init 은 앞에서 본 대로 nonisolated 다.


클로저와 Task

클로저는 선언이 아니라서 규칙이 따로 있다. @Sendable 이 아닌 클로저는 둘러싼 컨텍스트의 isolation 을 따르고, Task {} 도 그 규칙을 따른다. Task.detached 와 nonisolated 함수 안의 Task 는 그렇지 않다. 한 파일에 네 모양을 모았다.

Closures.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func f() {
  Task {
    print("Task in f")
  }

  Task.detached {
    print("detached in f")
  }

  let local = {
    print("local closure in f")
  }
  local()
}

nonisolated func g() {
  Task {
    print("Task in g")
  }
}

f() 는 철자 없는 함수이고 g() 는 nonisolated 함수다. f() 안에 클로저가 셋 있다. 첫째는 Task {} 에 넘긴 클로저, 둘째는 Task.detached 에 넘긴 클로저, 셋째는 local 에 담아서 바로 부르는 클로저다. 각 클로저의 isolation 을 SIL 에서 읽었다. 먼저 MainActor 모드다.

1
2
3
4
5
6
7
8
f()                                           global_actor MainActor
closure #1 in f()                             global_actor MainActor
static MainActor.shared.getter                unspecified
print(_:separator:terminator:)                unspecified
closure #2 in f()                             @concurrent
closure #3 in f()                             global_actor MainActor
g()                                           nonisolated
closure #1 in g()                             @concurrent

같은 파일을 기본 Swift 6 모드로 읽으면 이렇다.

1
2
3
4
5
6
7
f()                                           unspecified
closure #1 in f()                             @concurrent
print(_:separator:terminator:)                unspecified
closure #2 in f()                             @concurrent
closure #3 in f()                             nonisolated
g()                                           nonisolated
closure #1 in g()                             @concurrent

두 출력을 표로 합친다. print 와 static MainActor.shared.getter 줄은 표준 라이브러리 쪽이라 뺐다.

선언MainActor 모드기본 Swift 6
f()MainActorunspecified
Task {} 의 클로저 (#1)MainActor@concurrent
Task.detached 의 클로저 (#2)@concurrent@concurrent
지역 클로저 (#3)MainActornonisolated
g()nonisolatednonisolated
g() 안의 Task 클로저@concurrent@concurrent

바뀌는 것은 f() 와 그 안의 클로저 #1 과 #3 이다. #1 은 기본 모드에서 Task 의 클로저가 @concurrent 로 찍힌다. f() 가 어느 actor 에도 묶이지 않아서 Task 가 isolation 을 물려받을 곳이 없기 때문이다. MainActor 모드에서는 f() 가 main actor 라서 Task 의 클로저도 main actor 에서 돈다. #3 은 같은 이유로 nonisolated 에서 MainActor 로 옮겨 간다. #2 는 두 모드 다 @concurrent 다. Task.detached 가 둘러싼 isolation 을 물려받지 않는 API 이기 때문이다. g() 는 직접 nonisolated 라고 적었으므로 두 모드 다 nonisolated 이고, 그 안의 Task 도 두 모드 다 @concurrent 다.

Task.detached 는 @concurrent 클로저를 만든다고 했다. 그 안으로 non-Sendable 값을 넘기면 어떻게 되는지가 ImplicitSendable.swift 다.

ImplicitSendable.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
final class Box {
  var value = 0
}

func start(_ box: Box) {
  Task.detached {
    await box.increment()
  }
}

extension Box {
  func increment() {
    value += 1
  }
}

Box 는 Sendable 이 아닌 클래스이고, start(_:) 가 Task.detached 안으로 그 인스턴스를 넘긴다. increment() 는 extension 의 메서드다. 기본 Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ImplicitSendable.swift:7:5: warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
 5 | func start(_ box: Box) {
 6 |   Task.detached {
 7 |     await box.increment()
   |     `- warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
 8 |   }
 9 | }

ImplicitSendable.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]
 4 | 
 5 | func start(_ box: Box) {
 6 |   Task.detached {
   |        `- 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]
 7 |     await box.increment()
   |               `- note: closure captures 'box' 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>
[#UnnecessaryEffectMarker]: <https://docs.swift.org/compiler/documentation/diagnostics/unnecessary-effect-marker>
[exit 1]

첫 줄은 경고다(await 뒤에 async 작업이 없다). 오류는 Task.detached 의 클로저가 box 를 잡아서 sending 매개변수로 넘기는데, box 가 현재 isolation 컨텍스트에서도 접근할 수 있다는 것이다. 이 검사는 SE-0414 글 의 region 검사이고, sending 은 SE-0430 글 에서 다뤘다. MainActor 모드에서는 이 오류가 사라진다.

1
[exit 0]

Box, increment(), start(_:) 가 전부 @MainActor 가 되었고, global actor 에 묶인 클래스는 Sendable 로 취급된다. 그래서 box 를 넘겨도 data race 가 아니라고 판단하고, 경고도 같이 사라진다. 통과한 이유는 box 가 안전한 값이어서가 아니라 main actor 에 묶였기 때문이다. await box.increment() 는 이제 main actor 로 돌아가는 호출이 되고, 그래서 await 가 의미를 갖는다.


어디서 도는가

여기까지는 “어디에 @MainActor 가 붙는가” 를 컴파일러에 물었다. 이번에는 실제로 돌려서 어느 큐에서 도는지를 본다. 질문은 SE-0461 글의 것과 같다. 함수 네 개를 부르고 각 함수가 어느 Dispatch 큐에서 도는지를 찍는다.

Where.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
import Dispatch

nonisolated func queue() -> String {
  String(cString: __dispatch_queue_get_label(nil))
}

func plainAsync() async {
  print("plainAsync()        \(queue())")
}

nonisolated func nonisolatedAsync() async {
  print("nonisolatedAsync()  \(queue())")
}

@concurrent func concurrentAsync() async {
  print("concurrentAsync()   \(queue())")
}

func plainSync() {
  print("plainSync()         \(queue())")
}

@main
struct Program {
  static func main() async {
    await plainAsync()
    await nonisolatedAsync()
    await concurrentAsync()
    await Task.detached {
      await plainSync()
    }.value
  }
}

queue() 는 현재 스레드가 서비스하는 Dispatch 큐의 label 을 돌려준다. plainAsync() 는 아무것도 안 붙은 async 함수, nonisolatedAsync() 는 nonisolated 를 직접 적은 async 함수, concurrentAsync() 는 @concurrent 함수, plainSync() 는 동기 함수다. Program.main() 은 최상위 진입점이라서 @MainActor 이고, 마지막 호출만 Task.detached 안에서 부른다. 이 plainSync() 는 detached 안에서 await 로 부르는데, 기본 모드에서는 plainSync() 가 nonisolated 동기 함수라 await 가 필요 없어서 경고가 난다.

1
2
3
4
5
6
7
8
9
10
Where.swift:30:7: warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
28 |     await concurrentAsync()
29 |     await Task.detached {
30 |       await plainSync()
   |       `- warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
31 |     }.value
32 |   }

[#UnnecessaryEffectMarker]: <https://docs.swift.org/compiler/documentation/diagnostics/unnecessary-effect-marker>
[exit 0]

세 판으로 컴파일해서 돌렸다. 기본 Swift 6 판과 MainActor 모드 판, MainActor 모드에 NonisolatedNonsendingByDefault 를 더한 판이다.

1
2
3
xcrun swiftc -parse-as-library -swift-version 6 Where.swift -o where
xcrun swiftc -parse-as-library -swift-version 6 -default-isolation MainActor Where.swift -o where-main
xcrun swiftc -parse-as-library -swift-version 6 -default-isolation MainActor -enable-upcoming-feature NonisolatedNonsendingByDefault Where.swift -o where-main-feat

기본 판의 실행 결과다.

1
2
3
4
plainAsync()        com.apple.root.default-qos.cooperative
nonisolatedAsync()  com.apple.root.default-qos.cooperative
concurrentAsync()   com.apple.root.default-qos.cooperative
plainSync()         com.apple.root.default-qos.cooperative

네 함수가 모두 com.apple.root.default-qos.cooperative 큐에서 돌았다. main() 이 main actor 이어도 철자 없는 async 함수는 SE-0338 의 규칙대로 main actor 를 떠난다. 동기 함수 plainSync() 는 Task.detached 안에서 불렀으니 그 큐에서 돈다.

MainActor 모드 판이다.

1
2
3
4
plainAsync()        com.apple.main-thread
nonisolatedAsync()  com.apple.root.default-qos.cooperative
concurrentAsync()   com.apple.root.default-qos.cooperative
plainSync()         com.apple.main-thread

plainAsync() 와 plainSync() 가 com.apple.main-thread 큐로 옮겨 갔다. 두 함수가 @MainActor 가 되었기 때문이다. plainSync() 는 Task.detached 안에서 불렀는데도 main 에서 돈다. plainSync() 가 @MainActor 라서 부르려면 main actor 로 건너가야 하고, 그래서 await 가 붙는다. nonisolated 라고 적은 nonisolatedAsync() 와 @concurrent 인 concurrentAsync() 는 그대로 cooperative 큐다.

여기에 NonisolatedNonsendingByDefault 를 더한 판이다.

1
2
3
4
plainAsync()        com.apple.main-thread
nonisolatedAsync()  com.apple.main-thread
concurrentAsync()   com.apple.root.default-qos.cooperative
plainSync()         com.apple.main-thread

nonisolatedAsync() 도 com.apple.main-thread 로 옮겨 갔다. SE-0461 의 기본값 변경이 nonisolated 를 적은 async 함수를 부른 쪽 actor 에서 돌게 하기 때문이다. concurrentAsync() 는 @concurrent 라서 여전히 cooperative 큐다.

SIL 에서 읽은 isolation 과 맞춰 보면 이렇다. Program.main() 은 두 모드 다 global_actor MainActor 이고, plainAsync() 와 plainSync() 는 기본 모드에서 unspecified, MainActor 모드에서 global_actor MainActor 다. nonisolatedAsync() 는 nonisolated, concurrentAsync() 는 @concurrent 이고 Task.detached 의 클로저는 @concurrent 다. 세 번의 실행을 한 그림으로 모았다.

기본 Swift 6 에서는 네 함수가 모두 cooperative 큐에서 돌고, MainActor 모드에서는 철자 없는 async 와 sync 가 main 으로 옮겨 가며, NonisolatedNonsendingByDefault 를 더하면 nonisolated async 도 main 에 남는다

이 실험에서 일어난 일은 이렇다. 철자 없는 async 함수와 동기 함수가 cooperative 큐에서 main-thread 큐로 옮겨 갔다. 계산이 무거운 함수라면 main actor 를 막는다. 그래서 그런 함수에는 @concurrent 를 적는다. 이 제안은 @concurrent 를 새로 만들지 않았고, SE-0461 이 만들어 둔 것을 쓴다.


nonisolated 로 빠져나가기

main actor 에서 빼내고 싶은 코드는 nonisolated 로 빠져나온다. 타입 전체를 빼는 문법이 SE-0449 의 nonisolated struct 다.

NonisolatedType.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nonisolated struct Parser {
  var text: String

  func tokens() -> [Substring] {
    text.split(separator: " ")
  }

  struct Token {
    var value: Substring
  }
}

@concurrent func parse(_ text: String) async -> Int {
  Parser(text: text).tokens().count
}

Parser 는 문자열을 쪼개기만 하는 구조체이고 nonisolated 로 적었다. Token 은 그 안의 중첩 타입이고, parse(_:) 는 @concurrent 라서 main actor 밖에서 Parser 를 쓴다. 두 모드 모두 통과한다.

1
[exit 0]
1
[exit 0]

MainActor 모드의 AST 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nonisolated internal struct Parser {
  internal var text: String
  nonisolated internal func tokens() -> [Substring] {
    return self.text.split(separator: " ")
  }
  internal struct Token {
    internal var value: Substring
    internal init(value: Substring)
  }
  nonisolated internal init(text: String)
}
@concurrent internal func parse(_ text: String) async -> Int {
  return Parser(text: text).tokens().count
}

Parser 에 nonisolated 가 있고, 그 멤버 tokens() 와 init 도 nonisolated 다. 중첩 타입 Token 에는 속성이 없는데, 바깥이 nonisolated 타입이라서 기본값을 받지 않는다. 이 규칙은 추론 규칙의 그림에서 오른쪽 칸에 든 “nonisolated 타입 안의 중첩 타입” 이다.

nonisolated 를 빼면 어떻게 되는지도 같은 코드로 보았다. NonisolatedTypeMissing.swift 는 struct Parser 앞의 nonisolated 만 뺀 코드다.

1
2
3
4
5
6
7
8
NonisolatedTypeMissing.swift:14:22: error: main actor-isolated instance method 'tokens()' cannot be called from outside of the actor
12 | 
13 | @concurrent func parse(_ text: String) async -> Int {
14 |   Parser(text: text).tokens().count
   |                      `- error: main actor-isolated instance method 'tokens()' cannot be called from outside of the actor
15 | }
16 | 
[exit 1]

Parser.tokens() 가 @MainActor 로 추론되어서, @concurrent 인 parse(_:) 에서 부를 수 없다. 같은 코드가 기본 모드에서는 통과한다.

1
[exit 0]

이 한 쌍이 MainActor 모드에서 라이브러리 같은 코드를 쓸 때의 경계다. 동시성을 일부러 쓰는 코드는 nonisolated 와 @concurrent 를 직접 적는다. MainActor 모드는 그 표시를 줄여 주지 않고, 표시하지 않았을 때의 기본값만 바꾼다.


프로토콜과 conformance

처음에 본 conformance 오류가 MainActor 모드에서 왜 사라지는지는 프로토콜 isolation 에서 나왔다. 이번에는 같은 파일 안에서 nonisolated 프로토콜과 MainActor 모드의 타입을 조합한다.

ConformanceUse.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
nonisolated protocol Describable {
  func describe() -> String
}

final class Counter: Describable {
  var count = 0
  func describe() -> String { "count = \(count)" }
}

nonisolated func show(_ d: some Describable) -> String { d.describe() }

func useOnMain() {
  print(show(Counter()))
}

nonisolated func useElsewhere(_ c: Counter) {
  print(show(c))
}

Describable 은 nonisolated 프로토콜이고, Counter 는 그것을 채택하는 클래스다. show(_:) 는 nonisolated 함수로 some Describable 을 받고, useOnMain() 은 철자 없는 함수, useElsewhere(_:) 는 nonisolated 함수다. 기본 모드에서는 모두 nonisolated 라서 통과한다.

1
[exit 0]

MainActor 모드에서는 Counter 가 @MainActor 이고 describe() 도 @MainActor 다. 프로토콜은 nonisolated 라고 직접 적었으니 그대로 두고, Counter 의 conformance 가 main actor 에 격리된 conformance 가 된다.

1
2
3
4
5
6
7
8
9
10
ConformanceUse.swift:17:9: error: main actor-isolated conformance of 'Counter' to 'Describable' cannot be used in nonisolated context [#IsolatedConformances]
15 | 
16 | nonisolated func useElsewhere(_ c: Counter) {
17 |   print(show(c))
   |         `- error: main actor-isolated conformance of 'Counter' to 'Describable' cannot be used in nonisolated context [#IsolatedConformances]
18 | }
19 | 

[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]

오류가 나는 곳은 useElsewhere(_:) 의 show(c) 한 줄이다. useOnMain() 은 main actor 에서 conformance 를 써서 통과한다. 이 오류는 SE-0470 이 정한 isolated conformance 의 규칙이다. main actor 에 격리된 conformance 는 nonisolated 문맥에서 쓸 수 없다. MainActor 모드에서 nonisolated 프로토콜을 채택한 main actor 타입의 conformance 는 isolated conformance 로 추론된다. 오류 문구가 “main actor-isolated conformance” 라고 부르는 것이 그 conformance 다. 요구사항을 nonisolated 로 바꿔서 어디서든 쓰게 하는 대신, conformance 를 main actor 안에 가두는 쪽을 고른 것이다.

Codable 도 같은 모양이다. 표준 라이브러리의 Encodable 은 nonisolated 프로토콜이다.

CodableUse.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation

struct Point: Codable {
  var x = 0
  var y = 0
}

func encodeHere(_ p: Point) throws -> Data {
  try JSONEncoder().encode(p)
}

nonisolated func encodeElsewhere(_ p: Point) throws -> Data {
  try JSONEncoder().encode(p)
}

Point 는 Codable 구조체이고, encodeHere(_:) 는 철자 없는 함수, encodeElsewhere(_:) 는 nonisolated 함수다. 기본 모드는 통과한다.

1
[exit 0]

MainActor 모드에서는 encodeElsewhere(_:) 쪽이 막힌다.

1
2
3
4
5
6
7
8
9
10
CodableUse.swift:13:21: error: main actor-isolated conformance of 'Point' to 'Encodable' cannot be used in nonisolated context [#IsolatedConformances]
11 | 
12 | nonisolated func encodeElsewhere(_ p: Point) throws -> Data {
13 |   try JSONEncoder().encode(p)
   |                     `- error: main actor-isolated conformance of 'Point' to 'Encodable' cannot be used in nonisolated context [#IsolatedConformances]
14 | }
15 | 

[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]

Point 의 Encodable conformance 가 main actor 에 격리되어서 nonisolated 함수에서 JSONEncoder().encode(p) 를 부를 수 없다. encodeHere(_:) 는 통과한다. 고치는 길은 Point 를 nonisolated struct 로 만드는 것이다. 이 모양의 오류가 라이브러리 쪽에서 어떻게 보였는지는 스레드 절에서 다시 나온다.


Sendable 을 물려받는 프로토콜

수정안이 더한 규칙이 이 절이다. 처음 제안은 “isolation 을 적지 않은 선언에 @MainActor” 였다. 그런데 Sendable 을 상속한 프로토콜을 채택한 타입에 @MainActor 가 붙으면, 그 타입은 Sendable 프로토콜의 요구사항을 main actor 로 격리된 채로 구현해야 한다. 수정안은 이 경우 기본값을 적용하지 않게 했다. 수정안 pitch 에서 Doug Gregor 는 Sendable 프로토콜 채택, 기본 isolation, nonisolated 멤버, 합성된 conformance 네 가지를 문제로 꼽았다(수정안 pitch #1, Douglas_Gregor). 이 규칙은 초안에서는 Sendable 상속 여부로 정하려다가, 같은 pitch 의 #6 에서 SendableMetatype 상속 여부로 바뀐다(수정안 pitch #6, Douglas_Gregor). Sendable 은 SendableMetatype 을 상속하는 프로토콜이라서 Sendable 을 상속한 프로토콜은 모두 이 규칙에 든다.

SendableProto.swift

1
2
3
4
5
6
7
nonisolated protocol Q: Sendable {
  func f()
}

final class D: Q {
  func f() {}
}

Q 는 Sendable 을 상속하는 nonisolated 프로토콜이고, D 는 그것을 채택한 final 클래스다. 두 모드 모두 통과한다.

1
[exit 0]
1
[exit 0]

MainActor 모드의 AST 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
nonisolated internal protocol Q : Sendable {
  nonisolated func f()
}

final internal class D : Q {
  final internal func f() {
  }
  @objc deinit {
  }
  internal init() {

  }
}

D 에도 f() 에도 @MainActor 가 붙지 않았다. Q 가 Sendable 을 상속하고 D 가 Q 를 직접 채택해서, D 는 기본값을 받지 않는다. Q 에서 nonisolated 를 빼도 규칙이 같을까. 프로토콜의 nonisolated 를 뺀 파일로 확인했다.

SendableProtoPlain.swift

1
2
3
4
5
6
7
protocol Q: Sendable {
  func f()
}

final class D: Q {
  func f() {}
}
1
[exit 0]

오류는 없다. AST 는 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@MainActor internal protocol Q : Sendable {
  @MainActor func f()
}

@MainActor final internal class D : Q {
  @MainActor final internal func f() {
  }
  @objc deinit {
  }
  nonisolated internal init() {

  }
}

nonisolated 를 뺀 프로토콜은 @MainActor 프로토콜이 되고, D 도 @MainActor 가 된다. 직접 채택한 타입이 기본값을 받지 않는 경우는 프로토콜을 nonisolated 로 적어서 main actor 에 묶이지 않게 한 쪽이다. D 가 final 이 아니면 Sendable 프로토콜을 채택할 수 없다는 오류가 규칙과 상관없이 따로 난다. SendableProtoNonFinal.swift 는 D 에서 final 만 뺀 코드다.

SendableProtoNonFinal.swift

1
2
3
4
5
6
7
nonisolated protocol Q: Sendable {
  func f()
}

class D: Q {
  func f() {}
}
1
2
3
4
5
6
7
8
SendableProtoNonFinal.swift:5:7: error: non-final class 'D' cannot conform to the 'Sendable' protocol
3 | }
4 | 
5 | class D: Q {
  |       `- error: non-final class 'D' cannot conform to the 'Sendable' protocol
6 |   func f() {}
7 | }
[exit 1]
1
2
3
4
5
6
7
8
SendableProtoNonFinal.swift:5:7: error: non-final class 'D' cannot conform to the 'Sendable' protocol
3 | }
4 | 
5 | class D: Q {
  |       `- error: non-final class 'D' cannot conform to the 'Sendable' protocol
6 |   func f() {}
7 | }
[exit 1]

두 모드 모두 SendableProtoNonFinal.swift:5:7 에 같은 오류가 난다.

CodingKeys 에 @MainActor 가 붙지 않는 이유가 이 규칙이다. 표준 라이브러리의 CodingKey 는 Sendable 을 상속하고, Sendable 은 SendableMetatype 을 상속한다. enum CodingKeys: CodingKey 는 본 정의에서 이 프로토콜을 직접 채택하니 기본값을 받지 않고, 그 바깥의 struct S 는 @MainActor 로 남는다. 제안서는 Alternatives 의 SendableMetatype 항목에서 CodingKeys 를 이 문제의 예로 들고, 같은 문제가 있는 것으로 Transferable 프로토콜과 @Model 매크로가 쓰는 key path 를 덧붙인다. 손으로 쓴 CodingKeys 가 아니라 Codable 이 합성하는 CodingKeys 도 같은지 CodingKeysSynth.swift 로 보았다.

CodingKeysSynth.swift

1
2
3
struct S: Codable {
  var a: Int
}

두 모드 모두 컴파일된다.

1
[exit 0]
1
[exit 0]

MainActor 모드의 AST 에서 S, 프로퍼티 a, CodingKeys 의 선언 줄만 남겼다.

1
2
3
@MainActor internal struct S : Codable {
  @MainActor internal var a: Int
  private enum CodingKeys : CodingKey {

합성된 CodingKeys 도 속성이 없고 S 와 a 는 @MainActor 다.

이 규칙이 “타입의 primary definition” 에서 직접 채택한 경우에만 적용된다는 점이 같은 파일 extension 에서 갈린다. SendableProtoExt.swift 는 같은 D 를 extension 으로 채택하게 한 코드다.

SendableProtoExt.swift

1
2
3
4
5
6
7
8
9
nonisolated protocol Q: Sendable {
  func f()
}

final class D {}

extension D: Q {
  func f() {}
}

기본 모드에서는 통과한다.

1
[exit 0]

MainActor 모드에서는 D 의 본 정의에 채택이 없으므로 D 는 @MainActor 가 되고, extension 의 conformance 가 막힌다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SendableProtoExt.swift:7:14: error: conformance of 'D' to protocol 'Q' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
 5 | final class D {}
 6 | 
 7 | extension D: Q {
   |              |- error: conformance of 'D' to protocol 'Q' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
   |              |- note: isolate this conformance to the main actor with '@MainActor'
   |              `- note: turn data races into runtime errors with '@preconcurrency'
 8 |   func f() {}
   |        |- note: main actor-isolated instance method 'f()' cannot satisfy nonisolated requirement
   |        `- note: mark instance method 'f()' 'nonisolated'
 9 | }
10 | 

[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]

오류는 “D 의 Q conformance 가 main actor 격리 코드로 넘어간다” 이고, f() 가 main actor 에 격리되어 nonisolated 요구사항을 만족시킬 수 없다는 노트가 따른다. 같은 파일의 extension 으로 채택해도 풀리지 않는다는 뜻이다. 수정안 수락 공지가 남은 논의로 꼽은 것이 이 지점이다. 수정안 리뷰에서 Douglas_Gregor 와 hborla 는 이 판단이 타입의 primary declaration 만 본다고 설명한다(수정안 리뷰 #8, #9). 스레드 절에서 다시 본다.


override 와 SDK 클래스

마지막 질문은 override 다. 슈퍼클래스가 nonisolated 이면 서브클래스의 override 도 nonisolated 여야 한다. 먼저 SDK 의 main actor API 를 부르는 쪽부터 본다.

SDKCall.swift

1
2
3
4
5
6
7
8
9
@MainActor
final class Screen {
  var title = ""
  static let shared = Screen()
}

func rename() {
  Screen.shared.title = "Home"
}

Screen 은 @MainActor 클래스로, SDK 가 제공하는 UI 타입을 흉내 낸 것이다. rename() 은 철자 없는 함수다. 기본 모드의 진단이다.

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
SDKCall.swift:8:17: error: main actor-isolated property 'title' can not be mutated from a nonisolated context
 1 | @MainActor
 2 | final class Screen {
 3 |   var title = ""
   |       `- note: mutation of this property is only permitted within the actor
 4 |   static let shared = Screen()
 5 | }
 6 | 
 7 | func rename() {
   |      `- note: add '@MainActor' to make global function 'rename()' part of global actor 'MainActor'
 8 |   Screen.shared.title = "Home"
   |                 `- error: main actor-isolated property 'title' can not be mutated from a nonisolated context
 9 | }
10 | 

SDKCall.swift:8:10: error: main actor-isolated static property 'shared' can not be mutated from a nonisolated context
 2 | final class Screen {
 3 |   var title = ""
 4 |   static let shared = Screen()
   |              `- note: mutation of this static property is only permitted within the actor
 5 | }
 6 | 
 7 | func rename() {
   |      `- note: add '@MainActor' to make global function 'rename()' part of global actor 'MainActor'
 8 |   Screen.shared.title = "Home"
   |          `- error: main actor-isolated static property 'shared' can not be mutated from a nonisolated context
 9 | }
10 | 
[exit 1]

rename() 이 nonisolated 라서 @MainActor 인 Screen.shared.title 을 고칠 수 없다. 앞의 Motivation 과 같은 이유다. MainActor 모드에서는 rename() 이 @MainActor 라서 통과한다.

1
[exit 0]

반대 방향 오류가 override 에서 난다. Foundation 의 NSObject 는 nonisolated 이고, 그 서브클래스가 description 을 override 한다.

OverrideSDK.swift

1
2
3
4
5
6
7
8
import Foundation

final class Item: NSObject {
  var title = "item"
  override var description: String {
    "Item(\(title))"
  }
}

기본 모드는 통과한다.

1
[exit 0]

MainActor 모드에서는 Item 이 @MainActor 가 되고, 그 안의 description 도 @MainActor 가 된다. NSObject.description 은 nonisolated 라서 override 의 isolation 이 달라진다. 부모 선언이나 프로토콜에서 물려받은 isolation 이 기본값보다 앞서는 것은 그것이 global actor 일 때뿐이다. 부모 멤버가 nonisolated 이면 물려받을 global actor 가 없어서 기본값 @MainActor 가 그대로 붙고, 그래서 override 와 부모의 isolation 이 어긋난다.

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
OverrideSDK.swift:5:36: error: main actor-isolated getter for property 'description' has different actor isolation from nonisolated overridden declaration
3 | final class Item: NSObject {
4 |   var title = "item"
5 |   override var description: String {
  |                                    `- error: main actor-isolated getter for property 'description' has different actor isolation from nonisolated overridden declaration
6 |     "Item(\(title))"
7 |   }

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX27.0.sdk/usr/include/objc/NSObject.h:43:38: note: overridden declaration is here
 41 | - (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
 42 | 
 43 | @property (readonly, copy) NSString *description;
    |                                      `- note: overridden declaration is here
 44 | @optional
 45 | @property (readonly, copy) NSString *debugDescription;

OverrideSDK.swift:5:16: error: main actor-isolated property 'description' has different actor isolation from nonisolated overridden declaration
3 | final class Item: NSObject {
4 |   var title = "item"
5 |   override var description: String {
  |                `- error: main actor-isolated property 'description' has different actor isolation from nonisolated overridden declaration
6 |     "Item(\(title))"
7 |   }

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX27.0.sdk/usr/include/objc/NSObject.h:43:38: note: overridden declaration is here
 41 | - (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
 42 | 
 43 | @property (readonly, copy) NSString *description;
    |                                      `- note: overridden declaration is here
 44 | @optional
 45 | @property (readonly, copy) NSString *debugDescription;
[exit 1]

오류가 둘이다. getter 의 isolation 과 프로퍼티의 isolation 이 각각 다르다고 한다. 노트는 SDK 의 NSObject.h 를 가리키며 “overridden declaration is here” 라고 한다. 고치는 길은 override 쪽을 nonisolated 로 만드는 것이다. description 이 title 을 읽으므로 title 도 어디서든 읽을 수 있어야 한다. OverrideSDKFix.swift 는 title 을 nonisolated let 으로 둔 코드다.

OverrideSDKFix.swift

1
2
3
4
5
6
7
8
import Foundation

final class Item: NSObject {
  nonisolated let title = "item"
  nonisolated override var description: String {
    "Item(\(title))"
  }
}
1
[exit 0]
1
[exit 0]

두 모드 모두 통과한다. 여기서 title 에 nonisolated 가 꼭 필요한지 보려고 OverrideSDKLet.swift 는 let title 만 남기고 nonisolated 를 뺐다. description 의 nonisolated override 는 그대로다.

OverrideSDKLet.swift

1
2
3
4
5
6
7
8
import Foundation

final class Item: NSObject {
  let title = "item"
  nonisolated override var description: String {
    "Item(\(title))"
  }
}
1
[exit 0]
1
[exit 0]

두 모드 모두 통과한다. 요점은 let 이다. 상수라서 어느 actor 에서 읽어도 안전하다. 이 오류가 @MainActor 를 직접 붙인 클래스에서도 나는지도 같이 보았다.

OverrideSDKMain.swift 는 Item 에 @MainActor 를 직접 붙인 코드다.

1
2
3
4
5
6
7
8
9
10
11
OverrideSDKMain.swift:7:13: warning: main actor-isolated property 'title' can not be referenced from a nonisolated context
 3 | @MainActor
 4 | final class Item: NSObject {
 5 |   var title = "item"
   |       `- note: property declared here
 6 |   override var description: String {
 7 |     "Item(\(title))"
   |             `- warning: main actor-isolated property 'title' can not be referenced from a nonisolated context
 8 |   }
 9 | }
[exit 0]

기본 Swift 6 모드에서는 description 의 override 가 오류 없이 지나가고, title 을 읽는 곳에서 경고 하나만 난다. description 이 슈퍼클래스를 따라 nonisolated 로 읽히고 title 은 @MainActor 클래스의 프로퍼티이기 때문이다. 같은 코드를 MainActor 모드로 컴파일하면 위와 같은 두 오류가 난다.

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
OverrideSDKMain.swift:6:36: error: main actor-isolated getter for property 'description' has different actor isolation from nonisolated overridden declaration
 4 | final class Item: NSObject {
 5 |   var title = "item"
 6 |   override var description: String {
   |                                    `- error: main actor-isolated getter for property 'description' has different actor isolation from nonisolated overridden declaration
 7 |     "Item(\(title))"
 8 |   }

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX27.0.sdk/usr/include/objc/NSObject.h:43:38: note: overridden declaration is here
 41 | - (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
 42 | 
 43 | @property (readonly, copy) NSString *description;
    |                                      `- note: overridden declaration is here
 44 | @optional
 45 | @property (readonly, copy) NSString *debugDescription;

OverrideSDKMain.swift:6:16: error: main actor-isolated property 'description' has different actor isolation from nonisolated overridden declaration
 4 | final class Item: NSObject {
 5 |   var title = "item"
 6 |   override var description: String {
   |                `- error: main actor-isolated property 'description' has different actor isolation from nonisolated overridden declaration
 7 |     "Item(\(title))"
 8 |   }

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX27.0.sdk/usr/include/objc/NSObject.h:43:38: note: overridden declaration is here
 41 | - (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
 42 | 
 43 | @property (readonly, copy) NSString *description;
    |                                      `- note: overridden declaration is here
 44 | @optional
 45 | @property (readonly, copy) NSString *debugDescription;
[exit 1]

@MainActor 를 직접 붙인 클래스에서도 MainActor 모드가 켜져 있으면 override 가 오류다. 같은 @MainActor 클래스인데 모드에 따라 결과가 다르다는 것이 이 실험의 요점이다.

같은 모듈 안의 클래스 상속에서도 오류가 난다. Override.swift 는 아무것도 안 붙인 Base 의 메서드를 @MainActor 서브클래스 Child 가 override 한다.

Override.swift

1
2
3
4
5
6
7
8
9
10
11
class Base {
  func update() {}
}

@MainActor
final class Child: Base {
  var value = 0
  override func update() {
    value += 1
  }
}

기본 Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
Override.swift:9:5: error: main actor-isolated property 'value' can not be mutated from a nonisolated context
 5 | @MainActor
 6 | final class Child: Base {
 7 |   var value = 0
   |       `- note: mutation of this property is only permitted within the actor
 8 |   override func update() {
 9 |     value += 1
   |     `- error: main actor-isolated property 'value' can not be mutated from a nonisolated context
10 |   }
11 | }
[exit 1]

오류는 value += 1 에 난다. update() 가 슈퍼클래스를 따라 nonisolated 로 읽히는데 value 는 @MainActor 클래스의 프로퍼티라서 고칠 수 없다. MainActor 모드에서는 오류가 다른 곳에 난다.

1
2
3
4
5
6
7
8
9
10
11
12
Override.swift:6:25: error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 1 | class Base {
   |       `- note: overridden declaration is here
 2 |   func update() {}
 3 | }
 4 | 
 5 | @MainActor
 6 | final class Child: Base {
   |                         `- error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 7 |   var value = 0
 8 |   override func update() {
[exit 1]

이번 오류는 Child 의 init() 에 난다. 쓰지 않은 init 이 @MainActor 가 되어서 nonisolated 인 Base.init() 과 isolation 이 다르다는 것이다. @MainActor 를 손으로 붙이지 않은 코드에서도 같은지 보았다. OverrideDefault.swift 는 Child 의 @MainActor 만 뺀 코드다.

1
[exit 0]
1
2
3
4
5
6
7
8
9
10
11
OverrideDefault.swift:5:25: error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 1 | class Base {
   |       `- note: overridden declaration is here
 2 |   func update() {}
 3 | }
 4 | 
 5 | final class Child: Base {
   |                         `- error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 6 |   var value = 0
 7 |   override func update() {
[exit 1]

기본 모드에서는 통과하고 MainActor 모드에서만 init() 오류가 난다. 서브클래스가 직접 init 을 쓰면 어떨까. OverrideInit.swift 는 override init() { super.init() } 를 더한 코드다.

1
[exit 0]
1
2
3
4
5
6
7
8
9
10
11
12
13
OverrideInit.swift:7:12: error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 1 | class Base {
   |       `- note: overridden declaration is here
 2 |   func update() {}
 3 | }
   :
 5 | final class Child: Base {
 6 |   var value = 0
 7 |   override init() { super.init() }
   |            `- error: main actor-isolated initializer 'init()' has different actor isolation from nonisolated overridden declaration
 8 |   override func update() {
 9 |     value += 1
[exit 1]

직접 쓴 override init() 에도 @MainActor 가 붙어서 같은 오류가 난다. 오류가 나는 자리가 쓰지 않은 init 에서 직접 쓴 init 으로 옮겨 갔을 뿐이다. MainActor 모드에서는 Base 도 @MainActor 인데, 부모가 없는 Base 의 쓰지 않은 init() 만 앞에서 본 규칙대로 nonisolated 로 남는다. 서브클래스 Child 의 init() 은 합성하든 직접 쓰든 @MainActor 라서, 부모의 nonisolated init() 과 isolation 이 맞지 않는다. override init() 앞에 nonisolated 를 적으면 풀린다.

OverrideInitFix.swift

1
2
3
4
5
6
7
8
9
10
11
class Base {
  func update() {}
}

final class Child: Base {
  var value = 0
  nonisolated override init() { super.init() }
  override func update() {
    value += 1
  }
}
1
[exit 0]

AST 로 보면 Base 와 Base.update(), Child 와 Child.update() 는 모두 @MainActor 이고, 두 init() 만 nonisolated 다. 같은 모듈의 클래스끼리는 update() 의 isolation 이 서로 맞는다. 맞지 않는 곳은 쓰지 않은 init 과 SDK 의 nonisolated 선언이다.


스레드에서 오간 이야기

이 제안의 포럼 스레드는 여섯 개다. pitch 24 개 글, 리뷰 30 개 글(#1 은 리뷰 공지, #29 는 수락 공지 링크, #30 은 빈 글), 수락 공지, 수정안 pitch 15 개 글, 수정안 리뷰, 수정안 수락 공지다. 오간 이야기를 주제별로 묶는다. 인용 표기는 앞 글들처럼 (스레드 #번호, 글쓴이) 로 적는다.


언어가 둘로 갈라지는가

가장 많이 나온 걱정은 이 모드가 언어를 둘로 가르지 않느냐는 것이다. 소스 파일만 보고는 코드가 맞는지 판단할 수 없게 된다는 지적이 여러 번 나온다. pitch 에서 xwu 가 소스에 표시가 없는 dialect 라는 점을 짚었다(pitch #2, xwu). amayers 는 명시적인 표시를 원했다(pitch #3, amayers). 리뷰에서 KeithBauerANZ 는 이 설정이 @MainActor 를 적는 수고를 줄이는 정도의 값어치인데 코드의 정답이 방언에 따라 달라지는 비용을 지운다고 보았고, 전역 변수까지 쓸 수 있게 만드는 것에 반대했다(리뷰 #2, KeithBauerANZ). 같은 글에서 켜는 쪽이 opt-in 이라 방향은 맞다고도 한다. ktoso 는 방언이 생기는 것이 아쉽지만 기본값을 조정하는 정도라고 보았고, 이 설정은 opt-in 이라서 swift package init 으로 만든 패키지에는 꺼 두는 것이 맞으며, 장난감 앱과 앱 개발자에게는 쓸모가 보인다고 했다(리뷰 #3, ktoso). 8675309 는 이 방언이 나중에 후회가 될 큰 변화라고 보았고, 넣을 거라면 Swift 7 에서 기본값도 바꾼다고 공개 약속해야 한다고 했다(리뷰 #7, 8675309). 나중에 코드 리뷰가 평문 diff 로 이뤄지는 점을 위험 분석이 빠뜨렸다고도 한다(리뷰 #18, 8675309). EngOmarElsayed 는 @MainActor 는 UI 를 위한 특수한 경우이지 기본값이 아니어야 한다고 했다(리뷰 #23, EngOmarElsayed).

hborla 는 같은 질문에 이 위험이 Vision 문서의 “language dialect” 항목에서 다뤄진다고 답했고, 제안서의 Alternatives 에도 upcoming feature 로 하는 안이 실려 있다고 했다(리뷰 #17, hborla). Douglas_Gregor 의 답이 가장 길다(리뷰 #21, Douglas_Gregor). 그는 이 제안을 지지한다고 먼저 밝히고, Swift 6 의 progressive disclosure 곡선을 매끄럽게 해야 하며 동시성은 그 곡선에서 “나중” 에 나와야 한다고 했다. 대부분의 코드는 자기가 어느 isolation 에서 도는지 신경 쓰지 않는데, 신경 쓰는 코드가 조금만 있어도 그 영향이 코드베이스 전체로 퍼진다는 것이 그가 보는 어려움이다. UI 스택과 전역 변수가 main-actor 의 씨앗을 코드베이스에 심고, 함수가 특정 actor 에서 돌아야 하는지는 인터페이스의 일부라서 그 확산을 멈출 방법이 없다고 한다. 모드를 영영 두 개로 두는 일과 그 모드에서 나오는 길이 걱정이라는 점도 인정하면서, 단일 스레드에서 data-race 없는 사용으로 가는 매끄러운 길이 목표라는 입장이다. 같은 글에서 SE-0461 이 언어가 요청 없이 동시성을 끌어들이던 유일한 곳을 고친다고 짚었다.

수락 공지는 리뷰 반응이 대체로 긍정적이었고, “mode” 를 더하는 것이 정말 필요한지에 대한 우려가 있었다고 적는다. Language Steering Group 도 비슷한 느낌이었지만 Swift 6 의 progressive disclosure 곡선을 매끄럽게 하려면 이 모서리를 다듬어야 한다고 판단했고, Doug 의 글이 그 입장을 잘 대변한다고 했다(수락 #1, scanon).


누가 켜고 싶어 하는가

켜고 싶다는 쪽의 목소리도 리뷰에 여럿 있다. Airbnb 의 cal 은 큰 앱에서 Swift Concurrency 와 Swift 6 모드를 받아들이는 데 크게 도움이 된다고 했다. 지금 feature 계층에서 하는 일이 “전부 @MainActor 로” 에 가까운데 번거롭고 시끄럽다는 이유다(리뷰 #5, cal). GetYourGuide 의 marinofelipe 는 feature, UI, presentation 모듈에 켜겠다고 했다(리뷰 #20, marinofelipe). Swift 강의를 하는 svanimpe 는 이런 기능이 “absolutely required” 라고 했다. progressive disclosure 를 지키려면 지금 Swift 6 는 가르치기 어려워서, 이 기능이 나올 때까지 Swift 5 모드에 머물겠다는 것이다(리뷰 #9, svanimpe). pitch 단계에서 davbeck 은 새 Xcode 앱 타깃에는 기본으로 켜져야 한다고 했다(pitch #18, davbeck). 지금 Xcode 템플릿이 그렇게 나온다는 것은 앞에서 본 SWIFT_DEFAULT_ACTOR_ISOLATION 설정에서 이미 보였다.

반대쪽에서는 이 모드가 필요한 코드가 무엇이냐가 계속 물렸다. crontab 은 낡은 OOP 코드에는 좋은 기본값이지만 새로 쓰는 SwiftUI 앱은 필요 없을 것이고, 구조적 동시성을 우회하게 부추기며, 이 옵션을 권하는 StackOverflow 답이 쏟아질 것이라고 걱정했다(리뷰 #8, crontab). 예제를 달라는 요청과 그 답은 아래 전역 변수와 최상위 코드 절에서 이어진다.


모듈 단위인가 파일 단위인가

적용 범위는 pitch 와 리뷰 모두에서 나왔다. KeithBauerANZ 는 파일 단위 설정이 더 낫고 Xcode 파일 템플릿에 넣을 수 있다고 했다(리뷰 #4, KeithBauerANZ). ktoso 는 파일 단위 CompilerSettings pitch 가 이 제안과 합쳐질 수 있다고 했다(리뷰 #3, ktoso). jlukas 는 최상위 코드와 @main 이 있는 파일에서만 켜고 싶다고 했다(리뷰 #19, jlukas). 앞에서 본 것처럼 제안서는 파일 단위를 Future direction 으로 남겼다.

범위를 줄이자는 제안도 있었다. KeithBauerANZ 는 클래스 타입과 전역 변수에만 적용하거나, 공개 선언이 아닌 것에만 적용하자고 했다(리뷰 #2, KeithBauerANZ). hborla 는 둘 다 받지 않았다. 클래스와 전역 변수에만 적용하면 @MainActor 가 전이되는 성질 때문에 틀어지고, 비공개 선언에만 적용하는 안은 한 실행 파일 프로젝트의 일부인 라이브러리를 생각하면 곤란하며 외부 라이브러리의 공개 API 는 명시적이어야 한다는 것이다(리뷰 #16, hborla). 같은 글에서 목표를 progressive disclosure(isolation 을 언제 마주치느냐)와 단일 스레드 코드의 false positive 감소로 정리하고, 안전하게 쓰는 가변 전역 변수는 문제없어서 없애는 것은 불가능한 안이라고 했다.

pitch 에서 allevato 는 새 설정 값 대신 DefaultActorIsolation 같은 typealias 를 소스에 쓰는 방식을 제안했다(pitch #4, #7, allevato). hborla 는 철자가 틀려도 유효한 코드가 되고, nonisolated 를 나타낼 방법을 따로 만들어야 하고, 타입 검사의 순환 문제가 있다고 답했다(pitch #8, hborla). jakepetroules 는 manifest API 로 enum 을 원했는데(pitch #21 와 #23, jakepetroules), hborla 는 값이 MainActor.self 와 nil 뿐이고 커스텀 global actor 는 대안으로 실려 있다고 답했다(pitch #22, hborla). 이 가운데 enum 안은 제안서의 Alternatives 에 실렸고 typealias 안은 실리지 않았다. 커스텀 global actor 항목은 pitch #8 보다 앞서 있던 항목이다.


deinit 과 마이그레이션

리뷰 초반에 Nickolas_Pohilets 가 deinit 이 isolated 가 되느냐고 물었다(리뷰 #6, Nickolas_Pohilets). hborla 는 그렇다고 답했다(리뷰 #17, hborla). 지금은 쓰지 않은 deinit 만 main actor 에서 돌고, 직접 쓴 deinit 은 isolated 를 적어야 한다. 앞의 init 과 deinit 절에서 본 그대로다.

마이그레이션 방향도 한 번 정리되었다. hborla 는 두 방향이 모두 가능하다고 했다. nonisolated 에서 MainActor 로 가는 쪽은 isolation 이 정해지지 않은 선언에 nonisolated 를 끼워 넣는 작업이고, MainActor 에서 nonisolated 로 가는 쪽은 더 까다로워서 모듈 전체의 분석이 필요하다는 것이다(리뷰 #22, hborla).


전역 변수와 최상위 코드

예제를 달라는 crontab 의 요청에 svanimpe 는 전역과 static 변수를 들었고, 초반 예제는 main.swift 하나로 시작한다고 답했다(리뷰 #10 와 #11, crontab 과 svanimpe). crontab 은 전역 변수가 있으면 최상위 코드가 따라오는데, 최상위 코드는 경험이 쌓이기 전에는 쓰지 말라고 가르치면 되지 않느냐고 물었다. Swift 가 이제 스크립트 언어도 OOP 우선 언어도 아니니 낡은 개념을 가르칠 이유가 없다는 것이다(리뷰 #12, crontab). Nobody1707 은 최상위 코드가 애초에 가르치기 쉽게 하려고 있는 것인데, 첫 수업에서 쓰지 말라고 가르치면 후퇴라고 했다(리뷰 #13, Nobody1707). crontab 은 Xcode Playground 에서는 최상위 코드와 변수가 문제없으니 기본 개념은 거기서 익히면 되고, 실제 앱을 만드는 순간 동시성의 영역에 들어선다는 것을 이해하면 된다고 답했다(리뷰 #14, crontab). 이 논쟁은 이 글의 첫 실험(전역 변수 두 개)이 왜 제안서의 첫 예이기도 한지를 보여 준다.


수정안에서 나온 라이브러리 작성자의 목소리

수락 뒤에 수정안이 따로 올라왔다. Doug 가 SE-0470 의 isolated conformance 추론을 다른 기능과 같이 써 보다가 규칙 몇 곳을 고쳐야 한다고 본 것이다(수정안 pitch #1, Douglas_Gregor). Andropov 는 여러 글에서 소스에 명시적인 표시가 남기를 원했고(수정안 pitch #2, #4, #10, #13, Andropov), Nickolas_Pohilets 는 읽기 어려워진다며 nonisolated 를 소스에서 보고 싶다고 했다(수정안 pitch #5, Nickolas_Pohilets). Doug 는 이 추론을 타입 추론에 빗댔고(수정안 pitch #3, Douglas_Gregor), Swift 6.2 베타가 나온 뒤로 “되어야 하는데 안 되는” main-actor 기본 코드에 대한 피드백이 많이 들어왔다고 했다. 라이브러리가 쓰는 프로토콜이 main-actor 기본값을 막을 수 있어야 한다는 이야기가 swiftlang/swift 의 이슈 #82249 에 정리되어 있다고 했다(수정안 pitch #6, Douglas_Gregor). 그 글에서 조건이 Sendable 상속에서 SendableMetatype 상속으로 바뀌고, 실험 flag 뒤에 컴파일러 구현이 올라갔다. 그는 CodingKeys 같은 타입에 nonisolated 를 적으라고 요구하면 동시성이 학습 곡선의 너무 이른 곳으로 당겨진다고 했다(수정안 pitch #14, Douglas_Gregor). 같은 글에서 bjhomer 가 든 접근 제어 비유에는, 접근 제어는 개발자가 타입에 public 을 적어서 그 모델을 이미 직접 택한 뒤에만 추가 표기를 요구한다고 반박했다.

수정안 리뷰는 2025-07-09 부터 07-15 까지 신속 리뷰로 진행되었다(수정안 리뷰 #1, scanon). gwendal.roue 가 라이브러리 작성자 입장에서 가장 많이 글을 남겼다(수정안 리뷰 #4, #5, #7, #10, #15, #16, #17). 같은 파일 extension 으로 채택한 경우, 중첩 타입, “identity” 개념, 매크로가 주제다. 그가 원한 것은 같은 파일에 선언한 conformance 도 기본값을 막는 규칙이다(수정안 리뷰 #7, gwendal.roue). Doug 는 가장 가까운 선례가 프로토콜에서 @MainActor 를 추론하는 규칙인데 그 규칙이 같은 파일 extension 을 보지 않는다고 답했고(수정안 리뷰 #8, Douglas_Gregor), hborla 는 프로토콜의 isolation 이 타입에 영향을 주는 것이 본 선언에 conformance 가 있을 때뿐인 일관된 규칙이 더 이해하기 쉽다고 했다(수정안 리뷰 #9, hborla). stephencelis 와 mbrandonw 는 매크로가 더한 conformance 가 추론에 반영되지 않는 점을 짚었다. stephencelis 는 extension 매크로가 타입에 직접 붙어 있으니 타입의 identity 로 볼 수 있다고 했고, 지금은 사용자가 nonisolated 를 직접 적어야 하는데 그 오류가 매크로 확장 안에 숨어 난해하다고 했다(수정안 리뷰 #13, stephencelis). mbrandonw 는 매크로에 defaultIsolationIsMainActor: true 같은 인자를 더하는 방식이 퍼지고 있다고 소개하면서, 그 인자를 모든 매크로가 더해야 하고 사용자가 인자를 줘야 한다는 것도 알기 어렵다고 지적했다(수정안 리뷰 #14, mbrandonw). 나중에 mbrandonw 는 Sendable 요구를 줄여서 두 모드를 모두 지원할 수 있게 되었고, isolated conformance 덕에 개선도 있었다고 덧붙였다(수정안 리뷰 #18, mbrandonw).

수락 공지는 수정안이 SE-0466 의 거친 모서리를 다듬는다는 데 폭넓은 동의가 있었다고 적는다. 같은 파일 extension 에 대한 논의가 남았고, conformance 를 extension 에 두려는 사람들의 걱정과 매크로와의 상호작용을 이해하지만 수정안의 동작이 사용성에서 의미 있는 개선이라고 판단했다고 한다(수정안 수락 #1, scanon).

그 뒤의 논의는 수락 스레드에 이어서 달렸다. gwendal.roue 는 2025-10-03 과 10-06 에 GRDB 와 sqlite-data 의 이슈를 연결하면서, Xcode 26 에서 main actor 기본값으로 나오는 새 프로젝트가 라이브러리 사용자에게 컴파일러 오류를 쏟아낸다고 적었다(수정안 수락 #2, #3, gwendal.roue). mbrandonw 는 두 가지를 구분했다. 이 sqlite-data 이슈는 최근 변경이 기본 main actor isolation 을 우연히 깨뜨린 것이고, 앞서 겪은 문제 대부분은 라이브러리의 프로토콜에 Sendable 을 덜 굳히는 쪽으로 고쳤다는 것이다(수정안 수락 #4, mbrandonw). 같은 글에서 SPM 이 .defaultIsolation(MainActor.self) 를 테스트에서 존중하지 않는 것처럼 보여서 이 모드의 자동 테스트가 어렵다는 점도 지적했다. 8675309 는 프로토콜 정의 자체가 actor 요구사항을 가지는 것에 대한 오래된 질문과 연결했다(수정안 수락 #5, 8675309). gwendal.roue 는 nonisolated 를 타입 앞에 붙여도 해결되지 않는 경우가 있다고 답했다(수정안 수락 #6, gwendal.roue).


기대 효과

  • 동시성을 쓰지 않는 코드의 오류가 줄어든다. 첫 실험의 전역 변수와 static 변수가 그 예다. 같은 코드가 기본 Swift 6 에서는 오류 둘이고 MainActor 모드에서는 오류가 없다.
  • 전파되던 @MainActor 를 손으로 붙이지 않아도 된다. SDK 의 main actor API 를 부르는 rename() 이 한 줄도 바뀌지 않고 통과했고, @Sendable 이 아닌 클로저와 Task {} 가 둘러싼 isolation 을 따라서 같은 모양이 된다.
  • non-Sendable 클래스를 Task.detached 로 넘기는 코드처럼, @MainActor 클래스가 Sendable 로 취급된다는 사실에 기대는 코드가 통과한다. 이 통과는 값이 안전해서가 아니라 main actor 에 묶여서라는 점은 알아 두어야 한다.
  • -default-isolation 은 모듈 단위라서 의존하는 라이브러리의 isolation 을 건드리지 않는다. Core 에 켜지 않았을 때 hits 의 오류가 그대로 났다.
  • Xcode 의 새 앱 프로젝트가 이 설정을 켠 채로 나오므로, 처음 앱을 만드는 사람은 @MainActor 를 적지 않고 시작한다.

다른 선택지는 왜 안 됐나

제안서가 검토한 대안과 스레드에서 나온 대안이다.

  • 커스텀 global actor 를 기본값으로: main actor 가 아닌 global actor 는 progressive disclosure 에 도움이 되지 않고, 오히려 main actor 에서 부르는 쪽에 비동기를 강요한다. 이 제안은 MainActor 만 받는다. 앞의 Flag.swift 실험에서 MyActor 가 invalid value 로 거부된 이유다.
  • upcoming feature 로: 모드 대신 upcoming feature 로 두는 안이다. main actor 는 라이브러리나 동시성이 많은 서버 앱에는 틀린 기본값이라서 택하지 않았다. 나중의 언어 모드가 기본값을 바꿀 가능성은 남아 있다.
  • @nonisolatedConformingTypes 속성으로: 프로토콜이 채택하는 타입을 nonisolated 쪽으로 밀게 하는 새 속성이다. 이 안은 opt-in 이라서 CodingKey 같은 기존 프로토콜이 모두 이 철자를 달아야 좋은 결과가 나온다. SendableMetatype 상속 여부는 이미 널리 있는 신호라서 더 많은 코드가 잘 돈다는 이유로 이쪽을 택했다. 명시 속성은 나중에 필요하면 더할 수 있다.
  • manifest API 를 enum 으로: DefaultActorIsolation 의 .mainActor 와 .nonisolated 를 받는 안이다. #isolation 에서 쓰는 값(MainActor.self 와 nil)과 똑같이 쓰는 쪽이 익숙하다는 이유로 택하지 않았다. enum 은 커스텀 global actor 로 확장할 수 있다는 것이 장점이지만, 앞의 첫 항목과 같은 이유로 제안서가 의도적으로 대안에 두었다.
  • 소스의 typealias 로(allevato): 철자가 틀려도 유효한 코드, nonisolated 를 나타낼 방법을 따로 만들어야 함, 타입 검사 순환 때문에 택하지 않았다(pitch #8, hborla). 제안서의 Alternatives 에는 실리지 않았다.
  • 적용 범위를 줄이는 안(KeithBauerANZ): 클래스와 전역 변수에만, 또는 비공개 선언에만 적용하는 안은 @MainActor 의 전이와 라이브러리 경계 때문에 택하지 않았다(리뷰 #16, hborla).

Swift 6 모드와 마이그레이션

옵션을 켜기 전까지 이 제안은 기존 코드를 깨지 않는다. 다만 모듈의 기본 isolation 을 바꾸는 일은 그 자체로 source incompatible 변경이다. 옮길 때 알아 둘 점을 호환성, 언어 모드, 되돌리기 순서로 본다.


소스 호환

제안서의 Source compatibility 는 모듈이나 소스 파일의 기본 isolation 을 바꾸는 일이 source incompatible 변경이라는 문장으로 시작한다. 기본값은 nonisolated 로 남아 있어서, 기존 프로젝트는 -default-isolation MainActor 나 defaultIsolation(MainActor.self) 를 직접 주기 전까지 똑같이 컴파일된다. 옵션이 없는 기본 모드의 결과는 이 글 곳곳의 “기본” 판 출력이 보여 준다. 반대로 모듈의 기본값을 MainActor 로 바꾸면 소스가 깨질 수 있다. 앞의 override 실험과 Codable 실험이 그 예다. 같은 코드가 기본 모드에서는 통과하고 MainActor 모드에서는 오류가 났다. ABI 에는 영향이 없다.


언어 모드와의 관계

Swift 5 모드에서도 옵션을 쓸 수 있다. 같은 코드를 세 언어 모드로 컴파일하면 오류의 강도가 다르다.

Swift5Mode.swift

1
2
3
4
5
func mainOnly() {}

nonisolated func caller() {
  mainOnly()
}

mainOnly() 는 철자 없는 함수이고, caller() 는 nonisolated 함수가 그것을 부른다. 옵션 없이 컴파일하면 세 모드 모두 아무 말도 하지 않는다.

1
2
3
=== Swift5Mode.swift [-swift-version 5]
=== Swift5Mode.swift [-swift-version 5 -strict-concurrency=complete]
=== Swift5Mode.swift [-swift-version 6]

MainActor 모드로 컴파일하면 mainOnly() 가 @MainActor 이므로 nonisolated 에서 동기로 부르는 호출이 문제가 된다.

1
2
3
4
5
6
=== -default-isolation MainActor Swift5Mode.swift [-swift-version 5]
Swift5Mode.swift:4:3: warning: call to main actor-isolated global function 'mainOnly()' in a synchronous nonisolated context [#ActorIsolatedCall]
=== -default-isolation MainActor Swift5Mode.swift [-swift-version 5 -strict-concurrency=complete]
Swift5Mode.swift:4:3: warning: call to main actor-isolated global function 'mainOnly()' in a synchronous nonisolated context [#ActorIsolatedCall]
=== -default-isolation MainActor Swift5Mode.swift [-swift-version 6]
Swift5Mode.swift:4:3: error: call to main actor-isolated global function 'mainOnly()' in a synchronous nonisolated context [#ActorIsolatedCall]

Swift 5 모드와 Swift 5 의 complete 검사에서는 경고이고, Swift 6 모드에서만 오류다. 마이그레이션이 이 순서로 진행된다는 뜻이다. SE-0337 글 이 다룬 점진적 검사 단계를 그대로 따른다.


되돌리기와 라이브러리

방향은 두 가지다. 기본값이 nonisolated 인 프로젝트를 MainActor 로 바꿀 때는 isolation 이 정해지지 않은 선언에 nonisolated 를 끼워 넣어서 지금 동작을 보존하면 된다고 hborla 가 정리했다. 반대 방향은 모듈 전체의 분석이 필요해서 더 까다롭다(리뷰 #22, hborla). 라이브러리 작성자에게는 선언의 isolation 을 바꾸는 일이 소스와 ABI 에 미치는 영향이 따로 있다. 제안서는 선언에 @MainActor 를 붙이거나 떼는 일의 adoption 영향이 이 제안으로 달라지지 않는다고 하고, Swift 마이그레이션 가이드의 Library Evolution 글 에 문서화되어 있다고 연결한다.


정리

  • -default-isolation MainActor (SwiftPM 에서는 .defaultIsolation(MainActor.self), Xcode 에서는 SWIFT_DEFAULT_ACTOR_ISOLATION) 를 주면 isolation 을 적지 않은 선언이 @MainActor 로 추론된다. 모듈 단위이고 기본값은 nonisolated 다. 값은 MainActor 와 nonisolated 뿐이다.
  • 전역 함수, 변수, 타입과 멤버, static 속성, 직접 쓴 init, 클로저, 프로토콜에 @MainActor 가 붙는다. actor 안쪽(actor 격리), 명시한 isolation, 부모 선언이나 프로토콜에서 물려받은 global actor, nonisolated 타입 안의 중첩 타입, global actor 를 가질 수 없는 선언(typealias, import, enum case, 접근자)은 기본값을 받지 않는다.
  • 구조체의 memberwise init 과 부모 클래스가 없는 클래스가 합성한 init 은 nonisolated 로 남는다. 서브클래스가 물려받는 init 은 @MainActor 라서 부모의 nonisolated init 과 충돌한다. deinit 은 쓰지 않으면 main actor 에서 돌고 직접 쓰면 nonisolated 다. isolated deinit 이 필요하면 직접 적는다.
  • @Sendable 이 아닌 클로저와 Task {} 는 둘러싼 isolation 을 따르고, Task.detached 와 nonisolated 함수 안의 Task 는 @concurrent 다. isolation 을 적지 않은 함수는 MainActor 모드에서 main-thread 큐로 옮겨 간다. nonisolated 라고 적은 async 함수와 @concurrent 함수는 그대로 cooperative 큐다. 계산이 무거운 코드는 @concurrent 로 되돌려 보낸다.
  • nonisolated 는 struct Parser 처럼 타입 앞에 붙여서 멤버와 중첩 타입까지 한 번에 뺀다. 빼지 않은 타입은 @concurrent 함수에서 부를 때 오류다.
  • 프로토콜은 @MainActor 가 되고, nonisolated 프로토콜을 채택한 main actor 타입의 conformance 는 isolated conformance 가 되어서 nonisolated 문맥에서 쓰면 오류다. SendableMetatype 을 상속한 프로토콜(Sendable 을 상속한 것 포함)을 본 정의에서 직접 채택한 타입은 기본값을 받지 않는다. 같은 파일 extension 은 해당되지 않는다.
  • SDK 의 nonisolated 선언을 override 하면 오류가 난다. 해당 멤버를 nonisolated 로 적고, 그 멤버가 읽는 프로퍼티는 let 으로 둔다.
  • 스레드는 방언 문제, 채택자의 요구, 모듈과 파일 단위, 수정안과 라이브러리 작성자의 목소리로 나뉜다. 수락 공지는 이 모드가 Swift 6 의 progressive disclosure 를 위해 필요하다는 판단을 밝힌다.
  • 소스 호환은 옵션을 켜기 전까지 깨지지 않지만, 모듈의 기본 isolation 을 바꾸는 일 자체가 source incompatible 변경이다(override 와 Codable 실험이 그 예). ABI 영향은 없다. Swift 5 모드에서는 경고, Swift 6 모드에서는 오류로 단계를 밟아서 옮긴다.

관련 글


참고자료

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