[SE-0401] Remove Actor Isolation Inference caused by Property Wrappers
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지는 실제로 컴파일해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0401
- 상태: Implemented (Swift 5.9)
- upcoming feature flag:
DisableOutwardActorInference(Swift 6 언어 모드에서는 기본으로 켜진다) - 저자: BJ Homer
- 리뷰 매니저: Holly Borla
- pitch: Pitch (2023-02-21)
- 리뷰: SE-0401 review thread (2023-06-16 시작, 06-30 종료)
- 수락: Accepted with modifications (2023-07-18, flag 이름만 바꿔서 수락)
한 줄 요약
property wrapper 하나가 그 wrapper 를 쓰는 타입 전체를 @MainActor 같은 global actor(프로그램 전체에 창구가 하나뿐인 actor)로 끌어당기던 추론 규칙을 Swift 6 에서 없앤다. 다만 그 wrapper 를 붙인 프로퍼티 자신의 isolation(그 코드가 어느 actor 위에서만 돌아야 하는지의 표시)은 그대로 남는다. 숨어 있던 isolation 이 사라지는 것이라 풀리는 코드도 있고, 숨은 isolation 에 기대던 코드는 새로 error 가 난다.
어떤 문제였나
Swift 5.5 가 actor 를 들여오면서 “이 코드는 어느 actor 위에서만 돌아야 한다” 를 타입 시스템(컴파일러가 코드의 종류와 쓰임을 검사하는 규칙)으로 표시하게 되었다. 이 표시를 isolation 이라고 부른다. 그런데 모든 곳에 손으로 표시해야 한다면 너무 번거롭다. 그래서 SE-0316(Global actors)은 몇몇 경우에 컴파일러가 알아서 isolation 을 붙여 주는 추론 규칙을 함께 넣었다. 이 글의 주인공은 그 규칙 중 하나다.
property wrapper 의
wrappedValue가 global actor 로 묶여 있으면, 그 wrapper 를 쓴 프로퍼티를 가진 struct 나 class 전체가 같은 global actor 로 추론된다.
“한 프로퍼티가 main actor 에서만 쓸 수 있는 물건이니, 그걸 품은 타입도 main actor 에서만 쓸 거다” 라는 짐작이다. 짐작이 맞을 때는 편하지만, 틀릴 때는 화면에 아무것도 적혀 있지 않은 isolation 때문에 에러가 엉뚱한 곳에서 난다. 눈에 보이지 않는 규칙이 문제였다.
property wrapper 란?
property wrapper 는 프로퍼티를 읽고 쓰는 방식을 한 번 정해 두고 여러 프로퍼티에 재사용하게 해 주는 문법이다. @propertyWrapper 를 붙인 타입을 만들고, 프로퍼티 앞에 그 이름을 @이름 으로 붙이면 된다. 비유하면 물건마다 같은 포장지를 씌우는 일이다. 포장지(wrapper)가 어떤 식으로 값을 넣고 꺼낼지 정하고, 안에 든 물건(프로퍼티의 값)은 그대로다.
이 글 내내 헷갈리지 않으려면 한 가지를 정확히 알아야 한다. @UIUpdating var intValue: Int = 0 이라고 한 줄을 쓰면 컴파일러는 프로퍼티를 두 개 만든다.
_intValue: wrapper 인스턴스(UIUpdating<Int>)를 담는 저장 프로퍼티(값을 실제로 메모리에 담는 프로퍼티)다. 이 저장 공간을 backing storage 라고 부른다. 이름 앞에 밑줄이 붙는다.intValue: 우리가 코드에서 쓰는 이름이다. 실제 값을 갖지 않고, 읽을 때는_intValue.wrappedValue를 읽어 오고 쓸 때는 거기에 쓰는 계산 프로퍼티(값을 담지 않고 읽고 쓸 때마다 다른 값을 거쳐 처리하는 프로퍼티)다.
아래는 이 글의 예제 파일 Counter.swift 의 앞부분이다. 제안서의 UIUpdating 을 그대로 옮기되 뒤에서 이유를 말할 두 가지(Sendable 제약과 명시적 init)를 더했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@propertyWrapper
struct UIUpdating<Wrapped: Sendable> {
@MainActor var wrappedValue: Wrapped
init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
struct CounterView {
@UIUpdating var intValue: Int = 0
func describe() -> String { "counter" }
}
propertyWrapper와 MainActor와 Sendable로 wrapper 만들기
@propertyWrapper는 The Swift Programming Language 의 Attributes 장에 나오는 속성(attribute)이다. 붙인 타입은wrappedValue라는 프로퍼티를 반드시 가져야 하고, 그 값이 wrapper 로 감싼 프로퍼티의 실제 값 역할을 한다.@MainActor는 앞에 붙은 선언을 main actor 에 묶는다. main actor 는 UI 를 그리는 메인 스레드(앱의 화면을 그리고 갱신하는 스레드)와 같은 자리를 가리키는 global actor 다. 여기서는wrappedValue하나만 묶었다. 따라서wrappedValue를 읽고 쓰는 코드는 main actor 위에서 돌아야 하고, 다른 곳에서 부르면 컴파일러가 막는다.Sendable은 “서로 다른 actor 나 스레드 사이로 안전하게 넘겨도 되는 타입” 이라는 표시다.Wrapped: Sendable은 wrapper 가 감쌀 값의 타입이 이 조건을 만족해야 한다는 제약이다.init이 어느 actor 에도 묶이지 않은 채 값을 받아 main actor 의 프로퍼티에 넣으니 그 값이 경계를 넘기 때문이다. 이 제약을 빼고 같은 파일을 Swift 6 모드로 컴파일해 보면init안의self.wrappedValue = wrappedValue줄에서main actor-isolated property 'wrappedValue' can not be mutated from a nonisolated context라는 error 가 난다. Swift 5 모드에서는 같은 문구 뒤에; this is an error in the Swift 6 language mode가 붙은 warning 으로 나온다. 이 제약을 넣은 이유가 그 warning 이 Swift 6 에서 error 가 되기 때문이다.
global actor 와 isolation 추론이란?
actor 는 자기 안의 상태를 한 번에 한 코드만 만지도록 지켜 주는 타입이다. 비유하면 창구가 하나뿐인 사무실이다. 줄을 서서 한 사람씩 처리하므로 서류가 뒤섞이지 않는다. 이 창구 안쪽의 코드가 “그 actor 에 isolated 되어 있다” 고 말한다. 바깥에서 창구 안쪽의 것을 쓰려면 await 로 줄을 서야 한다.
global actor 는 이런 창구가 프로그램 전체에 하나만 있고 어디서든 이름으로 부를 수 있는 actor 다. MainActor 가 가장 대표적이다. 타입에 @MainActor 를 붙이면 그 타입의 프로퍼티와 메서드가 전부 main actor 창구에 묶인다. 이 줄을 직접 쓰지 않았는데도 컴파일러가 붙여 주는 경우가 있고, 이를 isolation 추론이라고 한다. 대표적인 경우는 다음과 같다.
- 부모 클래스가
@MainActor면 자식 클래스도 그렇게 추론된다. @MainActor가 붙은 프로토콜을 타입 선언에서 바로 채택하면(extension 에서 채택하는 경우는 다르다) 채택한 타입이 그 isolation 을 받는다. SwiftUI 의View가 이 자리에 있는데 뒤에서 다시 본다.- 이 글의 대상인 property wrapper 규칙이다. 프로퍼티에서 시작해서 바깥의 타입으로 번지는 방향이다.
앞의 두 가지는 “위에서 아래로” 내려오는 추론이고, 마지막 하나는 “안에서 바깥으로” 번지는 추론이다. 이름에 나오는 outward 가 이 방향을 가리킨다. actor 의 동작을 처음 보는 독자라면 이 시리즈의 [SE-0337] Incremental migration to concurrency checking 과 [SE-0412] Strict concurrency for global variables 를 같이 보면 좋다.
nonisolated 문맥이란?
이 글의 에러 메시지에는 “nonisolated context” 라는 말이 계속 나온다. 어느 actor 에도 묶이지 않은 코드, 즉 특별한 표시가 없는 평범한 함수 안을 가리킨다. 사무실 비유로는 창구 바깥의 복도다. 복도에 선 코드가 창구 안쪽의 것을 await 없이 바로 부르려 하면 컴파일러가 막는다. 에러 메시지에 붙는 “synchronous” 는 그 함수가 async(await 로 기다릴 수 있는 비동기 함수라는 표시)가 아니라서 await 로 줄을 설 수도 없다는 뜻이다. 그래서 “synchronous nonisolated context 에서 main actor-isolated 인 것을 불렀다” 가 이 글에서 가장 자주 보게 될 에러다.
보이지 않는 @MainActor
위의 CounterView 를 쓰는 코드까지 붙인 Counter.swift 의 뒷부분이다. 앞의 UIUpdating 정의는 같다.
1
2
3
4
func nonisolatedCaller() {
let view = CounterView()
print(view.describe())
}
같은 파일을 세 가지 방식으로 컴파일해서 비교한다. 이 글의 모든 진단은 아래 명령으로 얻었다.
1
2
3
4
5
6
7
8
9
# Swift 5 언어 모드
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 5 Counter.swift
# Swift 5 언어 모드 + 이 제안서의 upcoming feature flag
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 5 \
-enable-upcoming-feature DisableOutwardActorInference Counter.swift
# Swift 6 언어 모드
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 6 Counter.swift
swiftc 옵션으로 진단만 뽑아 보기
| 옵션 | 하는 일 |
|---|---|
-emit-sil | 컴파일을 SIL(Swift 컴파일러가 만드는 중간 표현) 단계까지만 진행한다. 초기화 전 사용 검사처럼 이 단계에서 나오는 진단까지 모두 보려고 쓴다. |
-o /dev/null | 결과물을 어디에도 남기지 않는다. 진단 메시지만 보면 된다. |
-parse-as-library | 파일을 main.swift 같은 스크립트가 아니라 라이브러리 소스로 컴파일한다. 최상위에 실행할 문장이 없는 예제 파일에 쓴다. |
-swift-version 5 또는 6 | Swift 언어 모드를 고른다. 아래 마이그레이션 절에서 설명한다. |
-enable-upcoming-feature 이름 | 다음 언어 모드에서 기본이 될 기능 하나만 지금 모드에서 미리 켠다. |
-typecheck 는 쓰지 않았다. 타입 검사 단계까지만 도는 옵션이라 SIL 단계에서 나오는 진단을 놓친다.
Swift 5 모드로 컴파일하면 error 가 두 개 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Counter.swift:17:14: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
8 | }
9 |
10 | struct CounterView {
| `- note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
11 | @UIUpdating var intValue: Int = 0
12 |
:
14 | }
15 |
16 | func nonisolatedCaller() {
| `- note: add '@MainActor' to make global function 'nonisolatedCaller()' part of global actor 'MainActor'
17 | let view = CounterView()
| `- error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
18 | print(view.describe())
19 | }
Counter.swift:18:14: error: call to main actor-isolated instance method 'describe()' in a synchronous nonisolated context [#ActorIsolatedCall]
11 | @UIUpdating var intValue: Int = 0
12 |
13 | func describe() -> String { "counter" }
| `- note: calls to instance method 'describe()' from outside of its actor context are implicitly asynchronous
14 | }
15 |
16 | func nonisolatedCaller() {
| `- note: add '@MainActor' to make global function 'nonisolatedCaller()' part of global actor 'MainActor'
17 | let view = CounterView()
18 | print(view.describe())
| `- error: call to main actor-isolated instance method 'describe()' in a synchronous nonisolated context [#ActorIsolatedCall]
19 | }
코드 어디에도 @MainActor 가 없는 CounterView 의 init() 과 describe() 가 main actor-isolated 라고 한다. 첫 error 의 note(10:8)는 init() 에 대한 것이고 struct CounterView 줄을 가리킨다. 컴파일러가 만든 init() 은 소스에 따로 적힌 줄이 없어서 타입 선언 자리를 대신 짚는 것이다. 두 번째 error 의 note 는 13행의 describe() 를 가리킨다. 게다가 describe() 는 intValue 를 건드리지도 않는다. 타입이 통째로 main actor 로 묶이다 보니, 무관한 메서드까지 따라 묶였다.
Swift 5 + flag 와 Swift 6 모드에서는 같은 파일이 진단 없이 통과한다. CounterView 가 더 이상 main actor 로 추론되지 않기 때문이다.
제안서의 UIUpdating 은 init 을 직접 쓰지 않고 memberwise init(프로퍼티를 인자로 받는 init 을 컴파일러가 자동으로 만든 것)을 쓴다. 그 코드(Original.swift)를 Swift 5 모드로 돌리면 위와 똑같이 13줄, 14줄에서 error 두 개가 난다. Swift 5 + flag 는 진단이 0 개다. 그런데 Swift 6 모드에서는 CounterView 쪽이 아니라 wrapper 정의 한 곳에서만 막힌다.
1
2
3
4
5
6
7
Original.swift:2:8: error: memberwise initializer for 'UIUpdating' cannot be both nonisolated and main actor-isolated
1 | @propertyWrapper
2 | struct UIUpdating<Wrapped> {
| `- error: memberwise initializer for 'UIUpdating' cannot be both nonisolated and main actor-isolated
3 | @MainActor var wrappedValue: Wrapped
| `- note: initializer for property 'wrappedValue' is main actor-isolated
4 | }
memberwise init 은 wrappedValue 를 채워야 하니 main actor 에 묶여야 하고, 동시에 wrapper 를 쓰는 쪽에서는 nonisolated 로 불려야 해서 두 요구가 부딪히는 것이다. 이 규칙은 이 제안서 이후 SE-0411 에서 들어왔다. 근거는 Swift 5 모드에서 -enable-upcoming-feature IsolatedDefaultValues 만 켜 보면 나온다.
1
2
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 5 \
-enable-upcoming-feature IsolatedDefaultValues Original.swift
1
2
3
4
5
6
7
Original.swift:2:8: warning: memberwise initializer for 'UIUpdating' cannot be both nonisolated and main actor-isolated; this is an error in the Swift 6 language mode
1 | @propertyWrapper
2 | struct UIUpdating<Wrapped> {
| `- warning: memberwise initializer for 'UIUpdating' cannot be both nonisolated and main actor-isolated; this is an error in the Swift 6 language mode
3 | @MainActor var wrappedValue: Wrapped
| `- note: initializer for property 'wrappedValue' is main actor-isolated
4 | }
같은 문구가 warning 으로 나온다. 이어서 14행 describe() 호출의 error 가 하나 더 나오는데 13행 init() 호출의 error 는 사라진다. SE-0411 이 init 을 nonisolated 로 보기 때문이다. 이 흐름은 [SE-0411] Isolated default value expressions 글에 있다. 그래서 이 글의 예제는 Wrapped: Sendable 제약과 명시적 init 을 넣은 Counter.swift 를 쓴다.
형제 함수가 깨지는 일
제안서가 가장 크게 내세우는 불만은 “spooky action at a distance”, 멀리 떨어진 곳이 이유 없이 달라진다는 점이다. Spooky.swift 로 재현했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@propertyWrapper
struct UIUpdating<Wrapped: Sendable> {
@MainActor var wrappedValue: Wrapped
init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
struct Panel {
@UIUpdating private var badge: Int = 0
func refresh() {
updateUI()
}
}
@MainActor func updateUI() {}
Swift 5 모드에서는 진단이 없다. Panel 이 badge 때문에 main actor 로 추론되어서 refresh() 도 main actor 위에 있고, 그래서 @MainActor 함수 updateUI() 를 그냥 부를 수 있다. 여기서 private 프로퍼티 badge 의 wrapper 를 지우거나 flag 를 켜면 같은 파일에서 refresh() 가 깨진다.
1
2
3
4
5
6
7
8
9
10
11
12
Spooky.swift:14:5: error: call to main actor-isolated global function 'updateUI()' in a synchronous nonisolated context [#ActorIsolatedCall]
11 | @UIUpdating private var badge: Int = 0
12 |
13 | func refresh() {
| `- note: add '@MainActor' to make instance method 'refresh()' part of global actor 'MainActor'
14 | updateUI()
| `- error: call to main actor-isolated global function 'updateUI()' in a synchronous nonisolated context [#ActorIsolatedCall]
15 | }
16 | }
17 |
18 | @MainActor func updateUI() {}
| `- note: calls to global function 'updateUI()' from outside of its actor context are implicitly asynchronous
badge 는 private 이다. private 프로퍼티는 그것을 직접 쓰는 코드에만 영향을 줘야 하는데, badge 를 한 번도 쓰지 않는 refresh() 의 컴파일 여부를 정하고 있었다. 제안서는 이를 형제(sibling) 함수가 깨지는 일이라고 부른다. SwiftUI 예제에서 쓴 표현이다.
다른 파일까지 번지는 일
제안서의 두 번째 예는 SwiftUI 와 상관없는 데이터베이스 라이브러리 이야기다. 번지는 범위가 파일 하나를 넘는다. 두 파일을 같이 컴파일해야 해서 db/DB.swift 와 db/Fetch.swift 로 나눠 두었다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@globalActor
actor DatabaseActor {
static let shared = DatabaseActor()
}
@propertyWrapper
struct DBParameter<T: Sendable> {
@DatabaseActor public var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
struct DBRow {}
struct DBConnection {
@DBParameter private var connectionID: Int = 0
func executeQuery(_ query: String) -> [DBRow] { [] }
}
1
2
3
4
5
6
7
8
9
10
@DatabaseActor
func fetchRows() async -> [DBRow] {
let connection = DBConnection()
return connection.executeQuery("SELECT 1")
}
func fetchFromAnywhere() -> [DBRow] {
let connection = DBConnection()
return connection.executeQuery("SELECT 1")
}
GlobalActor로 직접 global actor 만들기
@globalActor 는 MainActor 말고 나만의 global actor 를 만들 때 actor 타입에 붙이는 속성이다. 요구하는 것은 static let shared 하나로, 이 actor 인스턴스가 그 global actor 의 유일한 창구가 된다. @DatabaseActor 를 붙인 코드는 모두 이 shared actor 위에서 돈다. 여기서는 데이터베이스 접근 전용 창구를 만들었다.
DBParameter 의 wrappedValue 가 @DatabaseActor 이므로 Swift 5 모드에서는 DBConnection 전체가 @DatabaseActor 로 추론된다. 두 파일을 한꺼번에 컴파일하면 다음과 같다. -wmo 는 모듈(함께 컴파일되어 하나로 묶이는 소스 파일들의 단위) 전체를 한 번에 컴파일하는 옵션이다.
1
xcrun swiftc -emit-sil -wmo -o /dev/null -parse-as-library -swift-version 5 db/DB.swift db/Fetch.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
db/Fetch.swift:8:20: error: call to global actor 'DatabaseActor'-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
5 | }
6 |
7 | func fetchFromAnywhere() -> [DBRow] {
| `- note: add '@DatabaseActor' to make global function 'fetchFromAnywhere()' part of global actor 'DatabaseActor'
8 | let connection = DBConnection()
| `- error: call to global actor 'DatabaseActor'-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
9 | return connection.executeQuery("SELECT 1")
10 | }
db/DB.swift:17:8: note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
15 | struct DBRow {}
16 |
17 | struct DBConnection {
| `- note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
18 | @DBParameter private var connectionID: Int = 0
19 |
db/Fetch.swift:9:21: error: call to global actor 'DatabaseActor'-isolated instance method 'executeQuery' in a synchronous nonisolated context [#ActorIsolatedCall]
5 | }
6 |
7 | func fetchFromAnywhere() -> [DBRow] {
| `- note: add '@DatabaseActor' to make global function 'fetchFromAnywhere()' part of global actor 'DatabaseActor'
8 | let connection = DBConnection()
9 | return connection.executeQuery("SELECT 1")
| `- error: call to global actor 'DatabaseActor'-isolated instance method 'executeQuery' in a synchronous nonisolated context [#ActorIsolatedCall]
10 | }
11 |
db/DB.swift:20:8: note: calls to instance method 'executeQuery' from outside of its actor context are implicitly asynchronous
18 | @DBParameter private var connectionID: Int = 0
19 |
20 | func executeQuery(_ query: String) -> [DBRow] { [] }
| `- note: calls to instance method 'executeQuery' from outside of its actor context are implicitly asynchronous
21 | }
22 |
error 는 Fetch.swift 에서 나지만 note 는 파일 경계를 넘어 DB.swift 의 struct DBConnection 과 executeQuery 를 가리킨다. 원인은 다른 파일에 있다.
fetchFromAnywhere() 는 아무 actor 에도 묶이지 않은 동기 함수라서 DBConnection() 을 만들지도, executeQuery 를 부르지도 못한다. 막은 원인은 다른 파일의 DBConnection 안에 있는 private 프로퍼티 connectionID 하나다. 이 프로퍼티를 읽거나 쓰는 코드는 어디에도 없다.
반면 fetchRows() 는 @DatabaseActor 함수라서 세 모드 모두 통과한다. nonisolated 동기 메서드는 @DatabaseActor 함수 안에서도 그냥 부를 수 있으므로 fetchRows() 는 깨지지 않는다. 실제로 깨지는 쪽은 wrapper 가 있을 때의 바깥 호출(fetchFromAnywhere)이다. flag 를 켜거나 Swift 6 모드로 컴파일하면 두 파일 모두 진단이 없다.
제안서는 이 예에서 “private 프로퍼티를 바꾸는 일이 전혀 다른 파일의 컴파일 에러를 만들어서는 안 된다” 는 취지로, 이런 일이 Swift 에서 전례가 없다(unprecedented)고 쓴다. 파일을 나눠서 재현해 보면 그 말이 무슨 뜻인지 보인다. DB.swift 의 한 줄이 Fetch.swift 의 컴파일 여부를 정한다.
의도와 다르게 번지는 isolation
추론이 의도를 거스르는 경우도 있다. 제안서가 인용한 포럼 글에서 한 사용자는 프로퍼티 하나만 main thread 에 묶는 @OnMainThread wrapper 를 만들었다. Container.swift 가 그 상황이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@propertyWrapper
struct OnMainThread<T: Sendable> {
@MainActor var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
class Contained {
@OnMainThread var i = 1
}
class MyContainer {
let contained = Contained()
}
1
2
3
4
5
6
7
8
9
10
11
12
Container.swift:15:19: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
8 | }
9 |
10 | class Contained {
| `- note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
11 | @OnMainThread var i = 1
12 | }
13 |
14 | class MyContainer {
15 | let contained = Contained()
| `- error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
16 | }
i 만 main thread 에 묶고 싶었는데 Contained 전체가 @MainActor 가 되었고, 그것을 프로퍼티 초기값으로 만드는 MyContainer 의 선언까지 error 가 난다. 제안서의 표현으로 isolation 이 “viral” 하게, 의도한 범위 밖으로 번졌다. 직접 돌려 보면 flag 를 켜거나 Swift 6 모드에서는 두 클래스 모두 통과한다.
SwiftUI 에서 이 규칙이 보이던 자리
이 규칙이 가장 많이 보인 곳은 SwiftUI 였다. 제안서의 첫 예제가 그 상황이다. 아래 코드는 제안서에서 가져왔고, 주석의 error 문구도 제안서에 적힌 것이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct MyView: View {
@StateObject private var model = Model()
var body: some View {
Text("Hello, \(model.name)")
.onAppear { viewAppeared() }
}
// This function is inferred to be `@MainActor`
func viewAppeared() {
updateUI()
}
}
@MainActor func updateUI() { /* do stuff here */ }
여기서 @StateObject 를 @State 로 바꾸면 viewAppeared() 가 updateUI() 를 부르는 줄에서 Call to main actor-isolated global function 'updateUI()' in a synchronous nonisolated context 가 난다고 제안서는 말한다. model 을 전혀 쓰지 않는 함수가 프로퍼티 하나의 선언 방식 때문에 깨지는 것이다. @StateObject 의 wrappedValue 는 main actor 에 묶여 있고 @State 는 그렇지 않았기 때문이다.
그런데 지금 환경(Xcode 27 SDK)에서는 이 현상이 재현되지 않는다. 같은 모양으로 SwiftUIView.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 SwiftUI
final class Model: ObservableObject {
@Published var name = "Harold"
}
struct StateObjectView: View {
@StateObject private var model = Model()
var body: some View {
Text("Hello, \(model.name)")
.onAppear { viewAppeared() }
}
func viewAppeared() {
updateUI()
}
}
struct StateView: View {
@State private var model = Model()
var body: some View {
Text("Hello, \(model.name)")
.onAppear { viewAppeared() }
}
func viewAppeared() {
updateUI()
}
}
@MainActor func updateUI() {}
SwiftUI의 View와 StateObject와 State로 상태 만들기
View는 화면 조각을 나타내는 프로토콜이다.body에 화면을 어떻게 구성할지 쓴다.ObservableObject는 값이 바뀔 때 구독자에게 알려 줄 수 있는 class 의 프로토콜이고,@Published를 붙인 프로퍼티가 바뀔 때마다 알림이 나간다. 여기서는Model.name이 그렇다.@StateObject는ObservableObject인스턴스를 view 가 소유하게 한다. view 가 다시 만들어져도 인스턴스는 한 번만 만들어 유지한다.@State는 view 가 자기 안에 두는 값을 SwiftUI 가 관리하게 하는 wrapper 다. 여기서는@StateObject와 비교하려고 같은Model을 담았다.Text는 문자열을 보여 주는 view 이고,onAppear(perform:)는 그 view 가 화면에 나타날 때 넘긴 closure 를 실행한다.viewAppeared()를 부르기 위해 썼다.
결과는 세 모드(Swift 5, Swift 5 + flag, Swift 6) 모두 진단이 없다. 이유는 SDK 의 선언에 있다. Xcode 27 의 SwiftUICore.framework 안 SwiftUICore.swiftmodule/arm64e-apple-macos.swiftinterface 에서 가져온 선언이다. swiftinterface 는 컴파일된 라이브러리가 바깥에 공개하는 선언만 적어 둔 텍스트 파일이다.
1
2
3
@_typeEraser(DebugReplaceableView) @_typeEraser(AnyView) @preconcurrency @_Concurrency::MainActor public protocol View {
@frozen @propertyWrapper @preconcurrency @_Concurrency::MainActor public struct StateObject<ObjectType> : SwiftUICore::DynamicProperty where ObjectType : Combine::ObservableObject {
@frozen @propertyWrapper public struct State<Value> : SwiftUICore::DynamicProperty {
선언에 처음 보는 표기가 몇 개 있다. @_Concurrency::MainActor 는 MainActor 가 _Concurrency 모듈에서 왔다는 것을 모듈 이름까지 붙여 쓴 것이라 @MainActor 와 같다. @preconcurrency 는 Swift 6 이전 방식으로 쓰는 코드에서 isolation 위반이 나면 error 대신 warning 으로 낮춰 주는 표시다. @frozen 은 이 타입의 저장 프로퍼티 배치가 앞으로 바뀌지 않는다는 약속이고, DynamicProperty 는 SwiftUI 가 값이 바뀌는지 지켜봐야 하는 프로퍼티가 따라야 하는 프로토콜이다. @_typeEraser 는 이 글과 상관없다.
View 프로토콜 자체가 @MainActor 다. 그래서 View 를 채택한 StateObjectView 와 StateView 는 프로토콜 쪽에서 main actor isolation 을 받고, 프로퍼티가 @State 든 @StateObject 든 상관없이 같아진다. View 가 @MainActor 가 된 것은 Xcode 16(iOS 18 SDK)부터다. pitch 에서 bjhomer 도 Swift 5 에서 경고를 미리 내면 @ObservedObject 나 @StateObject 를 쓰는 모든 view 에 뜨게 되지만, SwiftUI.View 자체를 MainActor 로 만드는 SwiftUI 쪽 업데이트와 맞추면 완화될 수 있다고 했다(pitch #3). 제안서의 Source compatibility 절이 같은 말을 한다. 이 시리즈의 [WWDC24] Migrate your app to Swift 6 글에서 이 흐름을 더 볼 수 있다. 참고로 StateObject 자체는 @MainActor struct 이지만 State 에는 actor 표시가 없다. 이 글이 다루는 규칙은 이 차이 때문에 타입이 어긋나던 일이었다.
그러나 View 를 채택하지 않은 타입에서는 차이가 그대로 난다. PlainStruct.swift 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import SwiftUI
final class Model2: ObservableObject {}
// View 를 채택하지 않는 타입에 StateObject 를 쓴 경우
struct Holder {
@StateObject private var model = Model2()
func work() {
updateUI2()
}
}
@MainActor func updateUI2() {}
Swift 5 모드에서는 진단이 없고, flag 를 켜거나 Swift 6 모드로 돌리면 error 가 하나 난다.
1
2
3
4
5
6
7
8
9
10
11
12
PlainStruct.swift:10:5: error: call to main actor-isolated global function 'updateUI2()' in a synchronous nonisolated context [#ActorIsolatedCall]
7 | @StateObject private var model = Model2()
8 |
9 | func work() {
| `- note: add '@MainActor' to make instance method 'work()' part of global actor 'MainActor'
10 | updateUI2()
| `- error: call to main actor-isolated global function 'updateUI2()' in a synchronous nonisolated context [#ActorIsolatedCall]
11 | }
12 | }
13 |
14 | @MainActor func updateUI2() {}
| `- note: calls to global function 'updateUI2()' from outside of its actor context are implicitly asynchronous
무엇이 바뀌나
Swift 6 언어 모드에서는(그리고 Swift 5 모드에서 flag 를 켜면) 타입은 자기 프로퍼티가 쓰는 property wrapper 에서 isolation 을 추론하지 않는다. 제안서가 말한 해결책은 단순하다. 이 추론 단계를 통째로 끈다. 구현은 ActorIsolationRequest.getIsolationFromWrappers() 라는 컴파일러 함수가 어떤 추론도 내놓지 않게 하는 것이다.
아래 그림이 CounterView 에서 달라지는 범위를 보여 준다.
프로퍼티에 남는 isolation
“그럼 wrapper 의 main actor 표시는 아예 사라지나” 라는 질문이 리뷰에 나왔다(리뷰 #11, beccadax). 답은 아니다(#12, bjhomer). wrapper 가 붙은 프로퍼티 자신은 그 프로퍼티에 직접 @MainActor 를 쓴 것처럼 계속 isolated 이고 따로 붙일 표시도 필요 없다. 사라지는 것은 타입으로 번지는 쪽이다. 같은 작성자가 다른 글에서 더 정확하게 정리했다(#26). 지금은 isolation 이 추론되는 자리가 두 군데, 프로퍼티와 타입이고 이 제안서는 그중 타입 쪽만 지운다.
Backing.swift 로 직접 확인했다. thing() 은 nonisolated 를 명시한 메서드라서 어느 actor 에도 묶이지 않는다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@propertyWrapper
struct MainWrapper<T: Sendable> {
@MainActor var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
class Test {
@MainWrapper var x = 1
nonisolated func thing() {
print(_x)
print(x)
}
}
Swift 5 모드에서는 _x 와 x 둘 다 error 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Backing.swift:14:11: error: main actor-isolated property '_x' can not be referenced from a nonisolated context
9 |
10 | class Test {
11 | @MainWrapper var x = 1
| `- note: property declared here
12 |
13 | nonisolated func thing() {
14 | print(_x)
| `- error: main actor-isolated property '_x' can not be referenced from a nonisolated context
15 | print(x)
16 | }
Backing.swift:15:11: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
(이하 같은 모양)
flag 를 켜거나 Swift 6 모드로 컴파일하면 x(15:11) 하나만 남는다.
1
2
3
4
5
6
7
8
9
10
11
12
Backing.swift:15:11: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
9 |
10 | class Test {
11 | @MainWrapper var x = 1
| `- note: property declared here
12 |
13 | nonisolated func thing() {
14 | print(_x)
15 | print(x)
| `- error: main actor-isolated property 'x' can not be referenced from a nonisolated context
16 | }
17 | }
_x 는 wrapper 인스턴스를 담는 저장 프로퍼티라서 클래스 Test 가 isolation 을 추론하지 않으면 아무 actor 에도 묶이지 않는다. 그러니 nonisolated 메서드에서 읽어도 괜찮다. x 는 wrappedValue 가 main actor 에 묶인 계산 프로퍼티라서 여전히 막힌다. 리뷰 #29, #33 에서 bbrk24 가 말한 문제가 이 모습이다. bbrk24 는 의존성 주입 라이브러리 Dependiject 의 이슈를 링크했다. 그 이슈에서는 update() 를 nonisolated 로 두면 _observableObject 를 읽지 못해서, wrapper 를 손으로 풀어 쓰는(desugar) 우회를 했다. 처음에 bjhomer 는 원래 문제가 무엇이었는지 분명하지 않아 확답하기 어렵다고 했고(#31), bbrk24 가 “_observableObject 가 @MainActor 로 추론된 것이 문제였고 observableObject 만 그래야 했다” 고 설명하자(#33), 같은 모양의 테스트로 이 규칙이 들어오면 _observableObject 는 풀리고 observableObject 만 막힌다는 것을 보였다(#34). 그 테스트는 아래 TwoWrappers.swift 에서 다시 본다.
직접 붙인 @MainActor 와의 불일치
pitch 스레드에서 xwu 가 “UIUpdating 자체도 isolation 을 추론하지 않게 되는 것 아니냐” 고 물었다(pitch #2). bjhomer 는 처음에 “UIUpdating 타입 자체도 더 이상 isolated 가 아니게 된다” 고 답했다가(pitch #3), UIUpdating 은 Swift 5 에서도 원래 isolated 가 아니었다고 고쳤다(pitch #6). wrappedValue 에 @MainActor 를 직접 쓴 것은 프로퍼티에 wrapper 를 쓴 것이 아니라서 타입으로 번지지 않는다. 그는 “프로퍼티에 global actor 를 붙이는 것만으로 타입 전체가 isolated 되는 일은 한 번도 없었다” 고 설명하고, 이 불일치도 이 제안서가 풀어 주는 문제라고 덧붙인다.
Direct.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
@propertyWrapper
struct UIUpdating<Wrapped: Sendable> {
@MainActor var wrappedValue: Wrapped
init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
struct Direct {
@MainActor var x = 1
func describe() -> String { "direct" }
}
struct Wrapped {
@UIUpdating var x = 1
func describe() -> String { "wrapped" }
}
func callBoth() {
print(Direct().describe())
print(Wrapped().describe())
}
Swift 5 모드의 결과다.
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
Direct.swift:24:19: error: call to main actor-isolated instance method 'describe()' in a synchronous nonisolated context [#ActorIsolatedCall]
17 | @UIUpdating var x = 1
18 |
19 | func describe() -> String { "wrapped" }
| `- note: calls to instance method 'describe()' from outside of its actor context are implicitly asynchronous
20 | }
21 |
22 | func callBoth() {
| `- note: add '@MainActor' to make global function 'callBoth()' part of global actor 'MainActor'
23 | print(Direct().describe())
24 | print(Wrapped().describe())
| `- error: call to main actor-isolated instance method 'describe()' in a synchronous nonisolated context [#ActorIsolatedCall]
25 | }
26 |
Direct.swift:24:9: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
14 | }
15 |
16 | struct Wrapped {
| `- note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
17 | @UIUpdating var x = 1
18 |
:
20 | }
21 |
22 | func callBoth() {
| `- note: add '@MainActor' to make global function 'callBoth()' part of global actor 'MainActor'
23 | print(Direct().describe())
24 | print(Wrapped().describe())
| `- error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
25 | }
컴파일러는 같은 줄에서 뒤쪽인 24:19 의 describe() 를 앞쪽인 24:9 의 init() 보다 먼저 출력한다. 줄 안의 순서와 출력 순서가 같지 않다는 점만 알아 두면 된다.
23줄의 Direct().describe() 는 아무 문제 없이 통과하고, 24줄의 Wrapped() 의 init() 과 describe() 만 error 다. 두 타입은 x 의 main actor 표시를 직접 쓰느냐 wrapper 로 쓰느냐만 다르다. flag 를 켜거나 Swift 6 모드로 컴파일하면 둘 다 진단이 없고, 규칙은 하나로 맞는다. 프로퍼티의 isolation 은 프로퍼티에만 머문다.
원래 의도
리뷰에서 Karl 은 이 변경에 찬성하면서도, 규칙을 없애자고 하면서 “왜 있던 규칙인지” 를 모르는 채로 두는 것이 이상하다고 했다(#9). 그가 인용한 “이 upward inference 가 처음에 왜 제안되었는지 분명하지 않다” 는 문장은 리뷰 당시 제안서에 있던 것이고, 최종 본문에는 없다. 리뷰를 거치며 제안서 문장이 바뀐 사례다. SE-0316 의 저자인 Douglas Gregor 가 직접 답했다(#10). 당시 관찰은 @ObservedObject 처럼 main actor 에서만 쓸 수 있는 wrapper 가 있다면 그것을 품은 타입도 main actor 에서만 쓰일 가능성이 높다는 것이었고, @MainActor 를 일일이 쓰는 부담을 줄이려는 뜻이었다. 그는 다른 글에서(#14) 이 규칙을 구현한 사람으로서 처음의 직관이 상당히 틀렸다고 말하고, 이 규칙이 돕는 코드는 많지 않은데 혼란은 크다고 평가한다.
다른 선택지는 왜 안 됐나
이 제안서는 규칙을 없애는 방식을 두고 몇 가지 대안이 오갔다. Swift 5 모드에서 미리 warning 을 내는 안, 두 번째 wrapper 로 추론을 끊는 우회로, 그리고 upcoming feature flag 의 이름까지, 제안서 본문과 리뷰 스레드에서 갈린 부분을 차례로 본다.
Swift 5 에서 warning 내기
제안서의 Alternatives 절은 Swift 5 모드에서 “이 타입은 @StateObject 때문에 @MainActor 로 추론된다, Swift 6 에서 사라진다” 는 warning 을 내는 안을 검토했다. 두 가지 문제로 버려졌다.
- 실제로 깨지지 않는 코드에도 warning 이 많이 뜬다. pitch 에서 bjhomer 는
@ObservedObject나@StateObject를 쓰는 모든 SwiftUI view 에 뜰 것이라고 설명했다(pitch #3). - warning 을 끌 방법이 마땅치 않다. 타입을 일부러 isolated 하지 않게 남기고 싶은데, 당시에는
nonisolated struct라는 문법이 없었다(리뷰 #17, #23 의 설명). 타입에@MainActor를 붙이면 경고는 사라지지만 원하던 모양이 아니다. 당시 유일한 우회는 wrapper 를 손으로 풀어 쓰는(desugar) 것이었다. bbrk24 가 링크한 Dependiject 이슈의 코드가 그 모양이다(#29).
1
2
3
4
5
fileprivate var _observableObject: ObservedObject<ErasedObservableObject>
@MainActor internal var observableObject: ErasedObservableObject {
return _observableObject.wrappedValue
}
wrapper 문법을 버리고 backing storage 를 직접 만든 다음 계산 프로퍼티에만 @MainActor 를 붙여서, isolation 이 타입으로 번지지 않게 하는 방식이다. 수락 글도 warning 이 안 꺼지는 사례로 “desugaring the property wrapper to mark the computed property as @MainActor” 를 든다. 한편 #23 에서 bjhomer 가 “별도 제안” 이라고 미룬 nonisolated struct 는 뒤에서 SE-0449 가 된다.
수락 글도 같은 판단이다. Language Steering Group(Swift 언어의 방향을 정하는 그룹)은 warning 이 오히려 코드 churn(코드를 계속 고쳐야 하는 변경 부담)을 늘린다고 보았고, 이 변화를 미리 보고 싶은 사람은 upcoming feature flag 로 진단을 켜면 된다고 했다.
이후 Swift 6.1 의 SE-0449(Allow nonisolated to prevent global actor inference)가 타입에도 nonisolated 를 쓸 수 있게 해서 이 문제를 풀었다. NonisolatedType.swift 로 직접 돌려 봤다.
1
2
3
4
5
6
7
8
9
10
nonisolated struct CounterView {
@UIUpdating var intValue: Int = 0
func describe() -> String { "counter" }
}
func nonisolatedCaller() {
let view = CounterView()
print(view.describe())
}
(UIUpdating 정의는 Counter.swift 와 같다.) 세 모드 모두 진단이 없다. Swift 5 모드에서도 nonisolated 가 추론을 끊어서, Counter.swift 에서 error 가 나던 nonisolatedCaller() 가 통과한다.
두 번째 wrapper 로 추론 끊기
pitch 에서 xwu 가 우회로를 하나 냈다(pitch #2). 다른 global actor 에 묶인 wrapper 를 하나 더 붙이면 타입이 두 actor 사이에서 하나를 고르지 못해서 추론이 일어나지 않는다. bjhomer 는 첫 답에서 “그렇게 하면 된다” 고 인정하면서도, 컴파일러가 fix-it(에러와 함께 제안하는 자동 수정)으로 내놓기는 어렵다고 했다. 쓰이지 않는 private global actor 를 경우마다 새로 선언해야 하기 때문이다(pitch #3).
리뷰에서 같은 이야기가 다시 나왔다. xwu 가 Swift 5 에서 경고를 내자는 쪽의 근거로 이 우회로를 들자(#30), bjhomer 는 두 이유를 들었다(#32, 07-04). 하나는 fix-it 이 global actor 를 새로 선언해야 해서 너무 침습적(invasive)이고 직관적이지 않으며 문서화되어 있지도 않다는 것이다. 다른 하나는 쓸데없는 두 번째 wrapper 는 Swift 6 에서 바람직한 표기가 아니니 컴파일러가 권할 일이 아니라는 것이다. 과거의 경고는 새 표기로 미리 옮기도록 돕는 것이었는데, 이 우회로는 그 새 표기가 아니라는 말이다. 그 뒤에 xwu 가 직접 코드를 적었고(#36, 07-08), 이 방법은 예쁘지 않으며 Swift 6 동작을 원하는 사람은 flag 를 켜는 편이 낫다고 했다.
bjhomer 는 이 동작을 직접 보이기도 했다(#34). TwoWrappers.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
@globalActor
actor DBActor {
static let shared = DBActor()
}
@propertyWrapper
struct MainWrapper<T: Sendable> {
@MainActor var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
struct DBWrapper<T: Sendable> {
@DBActor var wrappedValue: T
init(wrappedValue: T) {
self.wrappedValue = wrappedValue
}
}
class Test {
@MainWrapper var x = 1
@DBWrapper var y = 2
nonisolated func thing() {
print(_x)
print(x)
print(_y)
print(y)
}
}
세 모드 모두 같은 결과다.
1
2
3
4
5
TwoWrappers.swift:30:11: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
(이하 note 생략)
TwoWrappers.swift:32:11: error: global actor 'DBActor'-isolated property 'y' can not be referenced from a nonisolated context
(이하 note 생략)
x 와 y 만 막히고 _x 와 _y 는 통과한다. 이 변경 이전의 Swift 5 모드에서도 그렇다. 두 wrapper 가 서로 다른 global actor 를 요구하면 Test 는 어느 쪽도 따르지 못해서, 이 제안서가 모든 타입에 적용하려는 모양과 같은 결과가 된다. 우회로가 이미 가능하다는 것과 그것을 공식 마이그레이션 경로로 삼는 일은 다르다. 이 안은 채택되지 않았다.
flag 이름
upcoming feature flag 이름은 리뷰 막바지에 여러 사람이 의견을 낸 주제였다. 수락 글도 이를 “minor constructive feedback” 이라고 부른다.
- 처음 이름은
DisableActorInferenceFromPropertyWrapperUsage였다(pitch #10). bjhomer 스스로 너무 길다고 인정했다. - James_Dempsey 가
DisablePropertyWrapperActorInference를 제안했다(#25). bjhomer 는 이름이 “모든 추론이 사라진다” 로 읽힐 수 있다고 답했다(#26). 프로퍼티 자신의 추론은 남기 때문이다. - benrimmington 이
Disable대신Restrict를(#27), James_Dempsey 가Reduced나Less를(#28) 제안했다. - bjhomer 는
DisableUpwardActorInference정도라면 괜찮겠다고 하고, 결정은 core team(당시 언어 결정을 맡던 Swift 프로젝트의 팀)에 맡겼다(#35). - 수락 글은 Language Steering Group 의 결정으로
DisableOutwardActorInference를 골랐다. 기존 이름보다 훨씬 짧으면서도, 멤버에서 시작한 추론이 바깥의 타입 전체로 퍼지는 문제의 동작을 잘 가리킨다는 이유였다.
호환성 평가
제안서는 오픈소스 프로젝트 8개(ACNHBrowserUI, Alamofire, Day One, Eureka, NetNewsWire, swift-nio, SwiftyJSON, XcodesApp)를 변경된 툴체인으로 돌려 봤고 전부 “Fully Compatible” 이라고 보고했다. 제안서 원문은 오픈소스 프로젝트 대부분이 property wrapper 를 전혀 쓰지 않는 라이브러리라고 말한다. 그래서 일부러 wrapper 를 쓰는 프로젝트를 찾아 골랐다고 한다. 목록을 보면 ACNHBrowserUI, Day One, NetNewsWire, XcodesApp 은 SwiftUI 의 wrapper 를 쓰고, Alamofire 는 자체 wrapper 가 있지만 actor 에 묶여 있지 않다. Eureka, swift-nio, SwiftyJSON 에는 wrapper 가 없다. concurrency checking(컴파일러가 concurrency 위반을 얼마나 검사할지 정하는 수준. Minimal 은 명시적으로 concurrency 를 쓴 코드만, Targeted 는 Sendable 등을 이미 적은 코드까지, Complete 는 모듈 전체를 검사한다. 자세한 설명은 [SE-0337] Incremental migration to concurrency checking 글에 있다)을 Minimal 이나 Targeted 로 둔 상태에서는 에러가 없었다. Complete 로 올린 상태에서는 이 변경과 상관없이도 에러가 많았고, 그 숫자에 이 변경이 에러를 몇 개 더 보탰을 수 있다는 단서가 붙는다.
리뷰에서 Douglas Gregor 는 자기들 쪽 호환성 시험에서는 잘 만들어진 코드가 몇 군데 깨졌다고 보고했다(#14). 놀랄 일도 문제도 아니고, 이 추론 규칙이 실제 코드에서 쓰이고 있다는 확인일 뿐이니 upcoming feature flag 와 Swift 6 모드로 단계적으로 들이는 것이 맞다는 이야기다. bjhomer 도 자기 샘플에서는 깨짐이 없었지만 더 큰 표본에서 나왔다고 해서 놀랍지 않다고 답했다(#17). 수락 글은 한 걸음 더 나가서, 에러 없이 동작이 바뀔 수 있는 upcoming feature 를 점검하는 별도의 마이그레이션 도구가 필요하다고 보고 그것을 따로 검토하겠다고 밝혔다.
개선했을 때의 기대 효과
위 실험을 표로 모으면 이렇다. 숫자는 -emit-sil 로 컴파일했을 때 나온 error 개수다.
| 예제 | Swift 5 | Swift 5 + flag | Swift 6 |
|---|---|---|---|
| Original | 2 | 0 | 1 |
| Counter | 2 | 0 | 0 |
| Container | 1 | 0 | 0 |
| Direct | 2 | 0 | 0 |
| db (DB.swift + Fetch.swift) | 2 | 0 | 0 |
| Backing | 2 | 1 | 1 |
| Spooky | 0 | 1 | 1 |
| PlainStruct | 0 | 1 | 1 |
| TwoWrappers | 2 | 2 | 2 |
| NonisolatedType | 0 | 0 | 0 |
| MainActorType | 0 | 0 | 0 |
| SwiftUIView | 0 | 0 | 0 |
Original 의 Swift 6 쪽 error 하나는 위에서 본 대로 이 제안서가 아니라 SE-0411 때문이다. TwoWrappers 는 이 변경과 무관하게 세 모드에서 같다. 이미 wrapper 가 두 개라 추론이 처음부터 일어나지 않았기 때문이다.
변화는 두 방향이다.
- 풀리는 쪽:
Counter,Container,Direct,db는 숨은 isolation 이 사라져서 nonisolated 코드가 타입을 쓸 수 있게 되었다.Backing은_x쪽 에러가 사라져서 둘에서 하나로 줄었다. - 드러나는 쪽:
Spooky와PlainStruct는 0 에서 1 로 늘었다. 숨은 main actor isolation 에 기대던 코드가 이제 에러로 나온다.
드러난 에러를 고치는 방법은 제안서의 Source compatibility 절이 권한 대로 타입에 @MainActor 를 직접 붙이는 것이다. 같은 결과를 Swift 5 에서도 낼 수 있으니 미리 붙여 둘 수 있다. MainActorType.swift 는 Spooky.swift 의 Panel 에 그렇게 한 것이다.
1
2
3
4
5
6
7
8
9
10
@MainActor
struct Panel {
@UIUpdating private var badge: Int = 0
func refresh() {
updateUI()
}
}
@MainActor func updateUI() {}
(UIUpdating 정의는 앞 예제와 같다.) Swift 5, Swift 5 + flag, Swift 6 세 모드 모두 진단이 없다. 추론이 있던 시절에도 없던 지금도 같은 뜻이므로, 동작이 바뀌는 시점에 영향을 받지 않는다.
Swift 6 언어 모드와 마이그레이션
이 제안서는 Swift 6 모드에서 기본으로 적용된다. 그 말이 무엇인지 먼저 짚고 가자.
언어 모드와 upcoming feature flag 란?
언어 모드는 같은 컴파일러가 소스를 어느 세대의 규칙으로 해석할지 정하는 설정이다. Swift 5 모드는 Swift 5 시절의 규칙을 유지하고, Swift 6 모드는 데이터 레이스(두 스레드가 같은 값을 동시에 만져서 결과가 뒤틀리는 버그) 안전을 비롯한 새 규칙을 한꺼번에 켠다. 새 규칙 중에는 이 글의 변경처럼 기존 코드를 깨뜨릴 수 있는 것이 있어서, 모드를 올리는 순간에만 적용하면 한 번에 고칠 양이 너무 많다.
그래서 새 규칙 하나하나에 upcoming feature flag 라는 스위치를 두었다. 다음 모드에서 기본이 될 기능을 지금 모드에서 하나만 미리 켜 보는 장치다. 가전제품의 새 기능을 설정 메뉴에서 하나씩 시험해 보는 것과 비슷하다. Swift 6 모드로 올리면 이 flag 들이 모두 켜진다.
이 변경의 flag 를 켜는 방법은 세 가지다.
- Xcode 에서: Build Settings 의 “Disable Outward Actor Isolation Inference”(
SWIFT_UPCOMING_FEATURE_DISABLE_OUTWARD_ACTOR_ISOLATION, Upcoming Features 분류)를 YES 로 둔다. Xcode 27 의Swift.xcspec에 이 설정이 정의되어 있고, 켜면-enable-upcoming-feature DisableOutwardActorInference가 컴파일러에 넘어간다. Swift 6 언어 모드에서는 이 설정을 쓸 필요 없이 항상 켜진다. - SwiftPM 에서:
swiftSettings: [.enableUpcomingFeature("DisableOutwardActorInference")] - 컴파일러에 직접:
-enable-upcoming-feature DisableOutwardActorInference
Xcode 의 “Approachable Concurrency”(SWIFT_APPROACHABLE_CONCURRENCY)는 DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances, InferSendableFromCaptures, NonisolatedNonsendingByDefault 다섯 가지를 한꺼번에 켠다. Xcode 27 의 새 프로젝트 템플릿은 이 설정이 YES 라서, 새 프로젝트는 Swift 5 모드여도 이 글의 동작이 이미 적용되어 있다. Swift.xcspec 와 템플릿의 TemplateInfo.plist 를 grep -r 로 찾아 확인한 내용이다. 이 설정이 생기기 전에는 pitch 에서 bjhomer 가 Other Swift Flags 에 같은 옵션을 넣으면 될 것이라고 추측한 방법이 있었다(pitch #12). 그 방법은 해 보고 한 말이 아니라고 본인이 밝혔다.
빌드가 통과해도 바뀌는 동작
이 변경의 진단은 두 방향이다. 새로 나는 error(Spooky, PlainStruct)와 사라지는 error(나머지)다. 그런데 수락 글이 따로 짚은 것은 이 변경 같은 upcoming feature 가 error 없이 동작만 바꿀 수 있다는 점이다. 리뷰 #23 에서 bjhomer 도 Swift 5 에서 미리 경고를 내면 “반드시 error 가 나는 경우만은 아니다(would not necessarily produce an error)” 라고 말했다. 이런 변화는 빌드가 막아 주지 못한다. 수락 글은 그래서 Swift 6 에서 동작이 바뀌는 코드를 훑어 주는 별도의 마이그레이션 도구가 필요하다고 보았다.
Silent.swift 가 그 예다. wrapper 하나를 가진 struct Loader 의 async 메서드가 어느 스레드에서 도는지 출력한다.
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
import Foundation
@propertyWrapper
struct UIUpdating<Wrapped: Sendable> {
@MainActor var wrappedValue: Wrapped
init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
struct Loader {
@UIUpdating var count: Int = 0
func load() async {
print("load() on main thread:", pthread_main_np() != 0)
}
}
@main
struct App {
@MainActor
static func main() async {
let loader = Loader()
await loader.load()
}
}
pthread_main_np() 는 지금 코드가 main thread 에서 도는지 알려 주는 C 함수라서, 0 이 아니면 main thread 다. load() 는 @MainActor 인 main() 에서 await 로 부른다. 네 가지 방식으로 진단과 실행 결과를 봤다. 진단은 앞에서처럼 -emit-sil -o /dev/null 로, 실행 결과는 실제로 빌드한 바이너리로 얻었다.
1
2
3
4
5
6
7
8
# 진단 (Swift 5, Swift 5 + flag, Swift 6, Swift 6 + NonisolatedNonsendingByDefault 모두 같은 형태)
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 6 \
-enable-upcoming-feature NonisolatedNonsendingByDefault Silent.swift
# 실행
xcrun swiftc -parse-as-library -swift-version 6 \
-enable-upcoming-feature NonisolatedNonsendingByDefault -o silent Silent.swift
./silent
| 모드 | 진단 | 실행 출력 |
|---|---|---|
| Swift 5 | 0 | load() on main thread: true |
Swift 5 + DisableOutwardActorInference | 0 | load() on main thread: false |
| Swift 6 | 0 | load() on main thread: false |
Swift 6 + NonisolatedNonsendingByDefault | 0 | load() on main thread: true |
Swift 5 에서는 Loader 가 main actor 로 추론되어서 load() 도 main actor 위에서 돈다. flag 를 켜면 추론이 사라져 load() 는 nonisolated async 메서드가 되고, Swift 6 은 이 메서드를 부른 쪽의 actor 가 아니라 전역 executor(특정 actor 에 묶이지 않은 코드를 돌리는 공용 실행 자리)에서 돌려서 main thread 를 벗어난다. 네 번째 줄의 NonisolatedNonsendingByDefault(SE-0461, Run nonisolated async functions on the caller’s actor by default)는 nonisolated async 메서드가 부른 쪽의 actor 에서 돌게 하는 flag 라서, 켜면 다시 true 가 된다.
결론은 이렇다. 빌드가 통과해도 async 메서드가 main thread 밖에서 돌 수 있다. flag 를 켠 뒤에는 컴파일 error 뿐 아니라 그 타입의 async 메서드가 어디서 도는지도 봐야 한다. 이 문제는 제안서가 인용한 Ole Begemann 의 SwiftUI Task and MainActor 글이 보여 주던 혼란과 같은 뿌리다.
해야 할 일
- flag 를 켜고 빌드해서 새로 나는
call to main actor-isolated ...error 를 찾는다. - 그 타입이 정말 main actor 에서만 쓰이는 것이라면 타입에
@MainActor를 붙인다. 에러 메시지의 note 가add '@MainActor' to make ... part of global actor 'MainActor'라고 해당 함수를 가리켜 주기도 한다. - 타입 전체를 묶을 필요가 없다면 그 함수 하나만
@MainActor로 두거나await로 부른다.await는 부르는 쪽 함수가async일 때만 쓸 수 있으니, 동기 함수라면 부르는 쪽도async로 바꾸거나Task안에서 불러야 한다. - flag 를 켠 뒤에는
Silent처럼 wrapper 를 가진 타입의async메서드가 어느 스레드에서 도는지도 확인한다. - SwiftUI 의
View를 채택한 타입은View프로토콜 자체가@MainActor라서 대부분 영향이 없다. 영향이 나오는 쪽은PlainStruct처럼View가 아니면서@StateObject같은 main actor wrapper 를 쓰는 타입이다.
ABI(컴파일된 바이너리끼리 서로 부를 때의 약속)에는 영향이 없다. 제안서는 actor isolation 이 런타임 calling convention, 즉 함수를 부를 때 인자를 어디에 담아 넘기고 반환값을 어디로 돌려받을지 정한 약속에 들어가지 않는다고 설명한다. 그래서 라이브러리 작성자가 이 변경 때문에 바이너리 호환성을 걱정할 일은 없다.
정리
- property wrapper 의
wrappedValue가 global actor 로 묶여 있으면 그것을 쓰는 타입 전체가 같은 actor 로 추론되던 규칙이, Swift 6 모드(Swift 5 에서는DisableOutwardActorInferenceflag)에서 사라진다. - 프로퍼티 자신의 isolation 은 그대로 남는다.
Backing.swift에서_x는 풀리고x는 계속 막히는 것으로 직접 봤다. - 숨은 isolation 이 풀어 주는 코드(
Counter,Container,Direct,db)와 숨은 isolation 에 기대다 새로 깨지는 코드(Spooky,PlainStruct)가 있고, 후자는 타입에@MainActor를 직접 붙이면 세 모드 모두에서 같은 뜻이 된다. - SwiftUI 의
View는 지금 SDK 에서@MainActor로 선언되어 있어서 이 변경의 영향을 크게 받지 않는다.
관련 글
- [SE-0411] Isolated default value expressions
- [SE-0412] Strict concurrency for global variables
- [SE-0337] Incremental migration to concurrency checking
- [WWDC24] Migrate your app to Swift 6
- SwiftUI 상태 관리 및 데이터 저장 비교
- [SE-0461] Run nonisolated async functions on the caller’s actor by default

