포스트

[SE-0449] Allow nonisolated to prevent global actor inference

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


제안서 정보

  • 번호: SE-0449
  • 상태: Implemented (Swift 6.1)
  • upcoming feature flag: 없음 (리뷰 때는 experimental feature GlobalActorInferenceCutoff 로 써 볼 수 있었고, 6.1 에서 정식 기능이 되었다)
  • 저자: Sima Nerush, Holly Borla
  • 리뷰 매니저: Tony Allevato
  • pitch: Pitch (2024-09-11, 글 9개)
  • 리뷰: Review (2024-10-02 시작, 10-16 까지)
  • 수락: Accepted (2024-10-22)
  • 전제 제안서: SE-0434 (global actor 에 묶인 타입의 사용성), SE-0313 (nonisolated 의 출발점), SE-0316 (global actor 와 추론 규칙)

한 줄 요약

protocol, extension, class, struct, enum 선언에 nonisolated 를 적어서 protocol conformance 와 상속에서 흘러 들어오는 global actor 추론을 그 선언에서 끊는다. 덤으로 저장 프로퍼티에 nonisolated 를 적을 수 있는 자리를 넓힌다. non-Sendable 타입의 저장 프로퍼티에 철자를 허용하고, Sendable 값 타입의 Sendable var 저장 프로퍼티에는 모듈 안에서 nonisolated 를 추론한다.


어떤 문제였나

@MainActor protocol 을 따르는 타입은 선언에 아무것도 적지 않아도 main actor 에 묶인다. 이 추론은 보통 편하지만, 타입을 일부러 nonisolated 로 두고 싶을 때가 문제다. 멤버마다 nonisolated 를 적는 길은 있어도 타입 전체의 추론을 끊는 직접적인 철자는 없었다. 제안서 Motivation 은 이 상황을 두 가지로 나눈다. conformance 가 extension 에 있을 때 쓰던 방법과, protocol 자체에서 추론을 끊고 싶을 때 쓰던 눈에 잘 안 띄는 우회다. 이 절은 둘을 6.4 컴파일러로 재현하고, 같은 일을 이 제안으로 하면 어떻게 달라지는지 본다.


global actor 추론이란?

actor 는 자기 안의 상태를 한 번에 한 코드만 만지게 하는 타입이고, global actor 는 프로그램 전체에 하나뿐인 actor 에 이름을 붙여 둔 것이다. 대표가 main thread 에 대응하는 @MainActor 다. 선언에 @MainActor 를 붙이면 그 선언은 main actor 의 창구 안에 들어가고, 쓰는 쪽은 이미 main actor 위에 있거나 await 로 줄을 서야 한다. 이 글에서 isolation 은 어떤 코드나 값이 어느 실행 영역(main actor, 다른 actor, 어디에도 묶이지 않은 영역)에 속하는지를 가리키는 말이다. 어디에도 묶이지 않는 것이 nonisolated 다. nonisolated 와 전역 변수 검사의 기초는 SE-0412 글에, global actor 에 묶인 타입의 nonisolated 규칙은 SE-0434 글에 있다.

추론은 “선언에 @MainActor 를 적지 않았는데도 컴파일러가 isolation 을 붙여 주는 것”이다. SE-0316 이 global actor 를 도입하면서 정한 규칙이 출처를 몇 가지 둔다. 이 글에서 다루는 출처는 셋이다.

  1. protocol conformance. @MainActor 가 붙은 protocol 을 선언에서 따르는 타입은 그 global actor 를 추론한다.
  2. protocol refinement. protocol Refined: GloballyIsolated 처럼 global actor 를 가진 protocol 을 확장한 protocol 도 그 isolation 을 이어받고, 그 protocol 을 따르는 타입은 또 이어받는다.
  3. 상속. global actor 를 가진 superclass 의 subclass 가 이어받는다.

반대편에는 SE-0313 이 만든 nonisolated 가 있다. SE-0313 은 nonisolated 를 함수와, class 의 Sendable let 저장 프로퍼티에 허용했고, SE-0434 는 global actor 에 묶인 값 타입의 var 저장 프로퍼티까지 넓혔다. 그러나 타입이나 protocol 선언에 nonisolated 를 붙이는 것은 되지 않았다. 이 제안이 그 자리를 연다.


Swift 언어 모드와 측정 방법

이 글의 모든 측정은 Xcode 27 의 Swift 6.4 컴파일러(Apple Swift version 6.4 (swiftlang-6.4.0.34.1)) 하나로 했다. 같은 컴파일러가 -swift-version 5 를 받으면 Swift 5 모드의 규칙으로, -swift-version 6 을 받으면 Swift 6 모드의 규칙으로 검사한다. Swift 5 모드에 -strict-concurrency=complete 를 더하면 concurrency 검사를 Swift 6 와 같은 범위로 넓히되 위반을 warning 으로 보여 준다. 이 글에서 “Swift 5” 는 Swift 5 모드 그대로, “complete” 는 거기에 이 옵션을 준 상태, “Swift 6” 은 Swift 6 모드를 가리킨다. 이 제안서에는 upcoming feature flag 가 없어서 세 가지만 비교한다. 단계별 설명은 SE-0434 글과 SE-0423 글에 있다. 따로 적지 않은 측정은 세 모드의 결과가 같다.

모든 진단은 -emit-sil 로 뽑았다. 타입 검사까지만 하는 -typecheck 는 SIL 단계에서 나오는 진단을 빼먹는다. 샘플은 전부 아래 두 가지가 들어 있는 Common.swift 와 함께 컴파일했다.

Common.swift

1
2
3
4
final class NonSendable { var value = 0 }

@MainActor
protocol GloballyIsolated {}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift X.swift

-o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 파일을 최상위 코드가 없는 일반 소스로 다루라는 옵션이며, -wmo 는 모듈 전체를 한 번에 처리하라는 옵션으로, 출력이 하나로 모여서 -o /dev/null 과 같이 쓸 수 있다. 진단 끝에 붙는 [#ActorIsolatedCall]: <https://...> 같은 참조 줄은 이 글에서 모두 뺐고, 나머지는 note 까지 원문 그대로다. 모듈 경계가 필요한 측정만 Common.swift 없이 모듈을 둘로 나눠서 따로 돌렸고, 그 명령은 해당 절에 적었다.


global actor 추론의 출처

세 출처를 한 파일에서 보면 이렇다. struct 는 conformance 로, 다른 struct 는 refinement 사슬로, class 는 상속으로 isolation 을 받고, 각각의 work() 를 nonisolated 함수에서 부른다.

Infer.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct S: GloballyIsolated {
  func work() {}
}

protocol Refined: GloballyIsolated {}

struct T: Refined {
  func work() {}
}

class Base: GloballyIsolated {}

class Sub: Base {
  func work() {}
}

nonisolated func use(s: S, t: T, sub: Sub) {
  s.work()
  t.work()
  sub.work()
}

Swift 5, complete, Swift 6 모두 같은 error 세 개가 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Infer.swift:18:5: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | struct S: GloballyIsolated {
 2 |   func work() {}
   |        |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
 3 | }
 4 | 
   :
16 | 
17 | nonisolated func use(s: S, t: T, sub: Sub) {
18 |   s.work()
   |     `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
19 |   t.work()
20 |   sub.work()

Infer.swift:19:5: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 6 | 
 7 | struct T: Refined {
 8 |   func work() {}
   |        |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from conformance to protocol 'Refined'
 9 | }
10 | 
   :
17 | nonisolated func use(s: S, t: T, sub: Sub) {
18 |   s.work()
19 |   t.work()
   |     `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
20 |   sub.work()
21 | }

Infer.swift:20:7: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
12 | 
13 | class Sub: Base {
14 |   func work() {}
   |        |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from inheritance from class 'Base'
15 | }
16 | 
   :
18 |   s.work()
19 |   t.work()
20 |   sub.work()
   |       `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
21 | }
22 | 

error 는 세 곳 모두 같은 말이다. main actor 에 묶인 work() 를 동기 nonisolated 문맥에서 불렀다는 것이다. 읽을 곳은 note 다. 첫 번째는 struct S 가 GloballyIsolated 를 따라서 main actor 가 추론되었다고 알려 준다. 두 번째가 눈여겨볼 자리다. struct T 는 Refined 를 따르는데, note 는 GloballyIsolated 가 아니라 Refined 를 가리킨다. 컴파일러는 바로 위 단계의 protocol 을 출처로 대고, 그 protocol 이 다시 어디서 isolation 을 받았는지는 따로 알려 주지 않는다. 사슬이 둘 셋으로 길어지면 출처를 찾으려고 protocol 을 하나씩 거슬러 올라가야 한다. 제안서 Motivation 이 말하는, global isolation 이 어디서 추론되는지 알기 어려워지는 불편이 이것이다. 세 번째는 상속이다. Sub 에 @MainActor 를 쓰지 않았지만 Base 가 GloballyIsolated 를 따르니 Sub 도 main actor 에 묶이고, note 는 inheritance from class 'Base' 라고 적는다.

이 세 흐름이 아래 절들이 끊으려는 대상이다. 이 글의 그림 1 이 같은 내용을 그린다.


extension 으로 우회하기

타입 선언이 아니라 extension 에서 conformance 를 선언하면 타입 자체에는 isolation 이 추론되지 않는다. 제안서 Motivation 이 첫 번째 우회로 드는 것이 이 방법이고, 그 대가는 witness 마다 nonisolated 를 적는 것이다. 제안서 코드를 그대로 돌렸다.

WorkaroundExt.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@MainActor
protocol P {
  var x: Int { get }
}

struct S {}

extension S: P {
  nonisolated var x: Int {
    get { 1 }
  }
  nonisolated func test() {
    print(x)
  }
}

nonisolated func use(s: S) {
  s.test()
  print(s.x)
}

진단은 0개다. S 에는 isolation 이 없고, extension 안의 x 와 test() 는 nonisolated 를 직접 적어서 use 에서 동기로 부를 수 있다. 문제는 이 철자가 protocol 요구 사항을 구현하는 멤버 하나하나에 필요하다는 것이다. 제안서도 요구 사항마다 nonisolated 를 적어야 한다고 설명한다. extension 에 nonisolated 를 붙이면 되지 않을까 싶지만, nonisolated extension S: P 로 바꿔 돌려도 witness 추론은 막히지 않는다. requirement() 호출만 9:5 error 가 나고 helper() 는 통과한다. 빠뜨린 멤버가 어떻게 되는지 보려고 요구 사항이 하나 있는 protocol 로 줄여서 돌렸다. 피치 xwu #3 이 이 부근을 묻는 대목이 있는데, 그 질문은 아래 “타입과 extension 의 conformance 가 만날 때” 절에서 받는다.

XwuWitnessControl.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@MainActor
protocol P {
  func requirement()
}

struct S {}

extension S: P {
  func requirement() {}
  func helper() {}
}

nonisolated func use(s: S) {
  s.requirement()
  s.helper()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
XwuWitnessControl.swift:14:5: error: call to main actor-isolated instance method 'requirement()' in a synchronous nonisolated context [#ActorIsolatedCall]
 7 | 
 8 | extension S: P {
 9 |   func requirement() {}
   |        |- note: calls to instance method 'requirement()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from conformance to protocol 'P'
10 |   func helper() {}
11 | }
12 | 
13 | nonisolated func use(s: S) {
14 |   s.requirement()
   |     `- error: call to main actor-isolated instance method 'requirement()' in a synchronous nonisolated context [#ActorIsolatedCall]
15 |   s.helper()
16 | }

extension 에서 conformance 를 선언하면 requirement 를 구현하는 멤버만 main actor 로 추론된다. requirement() 의 note 가 conformance to protocol 'P' 를 가리키고, 같은 extension 에 있는 helper() 는 진단이 없다. 추론은 extension 전체가 아니라 witness 에만 일어난다. 요구 사항이 아예 없는 GloballyIsolated 같은 protocol 을 extension 에서 따르면 아무것도 추론되지 않는다.

XwuControl.swift

1
2
3
4
5
6
7
8
9
struct S {}

extension S: GloballyIsolated {
  func inExtension() {}
}

nonisolated func use(s: S) {
  s.inExtension()
}

이 코드는 진단이 0개다. 그러니 extension 우회는 “타입에는 isolation 이 없고, witness 만 따로 nonisolated 로 적는다”는 두 단계 작업이다. 타입 선언에서 바로 따르면 타입 전체가 main actor 에 묶이니, conformance 를 어디에 선언하느냐가 isolation 을 좌우하게 된다. 타입의 isolation 을 바꾸려고 conformance 를 옮기는 것은 본래 목적이 아닌 부수 효과를 쓰는 셈이다.


global actor 를 부딪치게 하는 우회

두 번째 우회는 눈에 더 잘 안 띈다. 타입이 서로 다른 두 global actor 를 물려받으면 어느 쪽도 고르지 못하고 isolation 이 사라진다는 성질을 쓴다. 제안서는 일부러 쓸모없는 global actor 를 하나 정의해서 이 충돌을 일으키는, 아주 알아보기 어려운 우회를 소개한다. 제안서 Motivation 의 코드를 옮기고 RefinedProtocol 을 따르는 S 와 nonisolated 호출을 붙였다.

FakeActor.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
final class FakeExecutor: SerialExecutor {
  static let shared: FakeExecutor = .init()

  func enqueue(_ job: consuming ExecutorJob) {
    fatalError()
  }
}

@globalActor
public actor FakeGlobalActor: Sendable {
  public static var shared = FakeGlobalActor()

  private init() {}
  public nonisolated var unownedExecutor: UnownedSerialExecutor {
    FakeExecutor.shared.asUnownedSerialExecutor()
  }
}

@FakeGlobalActor
protocol RemoveGlobalActor {}

protocol RefinedProtocol: GloballyIsolated, RemoveGlobalActor {}

struct S: RefinedProtocol {
  func work() {}
}

nonisolated func use(s: S) {
  s.work()
}

globalActor 와 SerialExecutor 로 가짜 global actor 만들기

@globalActor 는 타입에 붙여 그 타입 이름을 global actor 로 쓰게 하는 속성이다. 속성이 붙은 타입은 actor 인스턴스를 내주는 static shared 를 가져야 하고, @FakeGlobalActor 처럼 그 이름을 선언에 붙이면 그 선언이 그 actor 에 묶인다. SerialExecutor 는 작업을 한 번에 하나씩 차례로 실행하는 실행기가 따라야 할 protocol 이다. 요구 사항은 일이 들어오는 입구인 enqueue 다. 이 입구가 받는 ExecutorJob 는 실행기가 돌려야 할 일 하나를 나타내는 값이고, consuming 은 이 값을 한 번만 쓰고 소진한다는 표시다. actor 는 unownedExecutor 로 자기가 어느 실행기에서 도는지 알리는데, 반환 타입 UnownedSerialExecutor 는 실행기를 retain 하지 않고 가리키는 참조다. asUnownedSerialExecutor() 가 SerialExecutor 에서 그 값을 만든다. 이 코드의 FakeExecutor 는 enqueue 가 호출되면 fatalError() 로 죽는다. 실제로 일을 돌리려는 것이 아니라 두 번째 global actor 라는 이름이 필요해서 만든 장식이다.

Swift 6 에서는 이렇게 나온다. Swift 5 에서는 진단이 없고, complete 에서는 같은 자리에 warning 이 나온다.

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

에러는 우회 자체가 아니라 제안서 코드에 있는 public static var shared 에서 난다. 전역 mutable 상태를 막는 Swift 6 의 검사(SE-0412 글)가 shared 를 잡았다. note 는 let 으로 바꾸라고 안내한다. 이 줄은 let 이어도 @globalActor 의 요구 사항을 만족하니 let 으로 고친 판을 돌렸다.

FakeActorLet.swift

이 파일은 위 코드에서 static var shared 한 줄만 static let shared 로 바꾼 것이고 나머지는 같다. 세 모드 모두 진단이 0개다. RefinedProtocol 이 GloballyIsolated 에서 main actor 를, RemoveGlobalActor 에서 FakeGlobalActor 를 물려받고, 둘이 충돌하니 컴파일러는 어느 쪽도 추론하지 않는다. 그래서 S 는 isolation 이 없고 use 에서 s.work() 를 동기로 부를 수 있다. 대조군은 FakeGlobalActor 쪽을 뺀 판이다.

FakeActorControl.swift

1
2
3
4
5
6
7
8
9
protocol RefinedProtocol: GloballyIsolated {}

struct S: RefinedProtocol {
  func work() {}
}

nonisolated func use(s: S) {
  s.work()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
FakeActorControl.swift:8:5: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 2 | 
 3 | struct S: RefinedProtocol {
 4 |   func work() {}
   |        |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from conformance to protocol 'RefinedProtocol'
 5 | }
 6 | 
 7 | nonisolated func use(s: S) {
 8 |   s.work()
   |     `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 9 | }
10 | 

가짜 global actor 가 없으면 RefinedProtocol 은 main actor 를 그대로 물려주고 S 의 work() 는 main actor 에 묶인다. 우회가 하는 일은 이 흐름을 일부러 어긋나게 하는 것이다.

이 우회가 코드로는 되지만 읽는 사람에게는 이상하다는 점은 피치에서도 나왔다. ktoso #2 는 처음 초안의 이 예제가 컴파일되지 않는다는 점을 짚었다. enqueue 는 actor 가 아니라 executor 에 있어야 한다는 것이고, 고친 PR 을 직접 보냈다. 같은 글에서 ktoso 는 “remove actor isolation trick” 이라고 부른 이 우회를 제대로 된 철자로 바꿔 주니 trick 이 퍼지는 것을 막는 데 도움이 되리라고 말한다. 이 제안으로 같은 일을 하면 이렇다.

NonisolatedProtoS.swift

1
2
3
4
5
6
7
8
9
nonisolated protocol RefinedProtocol: GloballyIsolated {}

struct S: RefinedProtocol {
  func work() {}
}

nonisolated func use(s: S) {
  s.work()
}

nonisolated protocol RefinedProtocol: GloballyIsolated {} 한 줄이다. 진단은 0개이고 S 의 work() 는 동기로 불린다. 가짜 actor, 가짜 executor, fatalError() 로 만든 장식이 모두 필요 없다.


무엇이 바뀌나

제안의 핵심은 문법 한 줄이다. 지금까지 nonisolated 는 함수, 프로퍼티, 변수 같은 멤버 수준 선언에만 붙었다. 이 제안은 그것을 protocol, extension, class, struct, enum 선언에도 붙일 수 있게 하고, 붙이면 그 선언에서 global actor 추론이 끊긴다. 피치 simanerush #1 이 처음 제안한 범위가 이것이고, 같은 글에 “and more” 라는 말도 있다. 최종안의 범위는 아래 절들에서 하나씩 측정한다.


nonisolated protocol

protocol 에 nonisolated 를 붙이면 그 protocol 은 GloballyIsolated 의 요구 사항은 그대로 갖되 isolation 은 물려받지 않는다. 제안서 코드를 그대로 돌렸다.

Proto.swift

1
2
3
4
5
6
7
8
nonisolated protocol Refined: GloballyIsolated {}

struct A: Refined {
  var x: NonSendable
  nonisolated func printX() {
    print(x) // okay, 'x' is non-isolated
  }
}

세 모드 모두 진단이 0개다. A 는 Refined 를 따르는데, Refined 가 nonisolated 라서 A 도 main actor 에 묶이지 않는다. 그래서 printX() 안에서 x 를 읽어도 된다. nonisolated 만 뺀 대조군은 이렇다.

ProtoControl.swift

1
2
3
4
5
6
7
8
9
10
ProtoControl.swift:6:11: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
2 | 
3 | struct A: Refined {
4 |   var x: NonSendable
  |       `- note: property declared here
5 |   nonisolated func printX() {
6 |     print(x) // okay, 'x' is non-isolated
  |           `- error: main actor-isolated property 'x' can not be referenced from a nonisolated context
7 |   }
8 | }

x 가 main actor 에 묶여 printX() 에서 읽을 수 없다. 두 파일의 차이는 첫 줄의 nonisolated 하나다. 이 한 줄이 Refined 에서 끊고 A 까지 흐르지 않게 한다.


nonisolated extension

extension 에 붙이면 그 extension 안의 멤버가 모두 nonisolated 가 된다. 위의 우회 1 이 멤버마다 적던 nonisolated 가 extension 한 곳으로 모인다. 제안서 코드를 돌렸다.

Ext.swift

1
2
3
4
5
6
7
8
9
10
11
nonisolated extension GloballyIsolated {
  var x: NonSendable { .init() }
  func implicitlyNonisolated() {}
}

struct C: GloballyIsolated {
  nonisolated func explicitlyNonisolated() {
    let _ = x // okay
    implicitlyNonisolated() // okay
  }
}

진단이 0개다. GloballyIsolated 를 확장하는 x 와 implicitlyNonisolated() 는 extension 이 nonisolated 라서 explicitlyNonisolated() 에서 동기로 쓸 수 있다. nonisolated 를 뺀 대조군은 이렇다.

ExtControl.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
ExtControl.swift:8:13: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
 1 | extension GloballyIsolated {
 2 |   var x: NonSendable { .init() }
   |       `- note: property declared here
 3 |   func implicitlyNonisolated() {}
 4 | }
   :
 6 | struct C: GloballyIsolated {
 7 |   nonisolated func explicitlyNonisolated() {
 8 |     let _ = x // okay
   |             `- error: main actor-isolated property 'x' can not be referenced from a nonisolated context
 9 |     implicitlyNonisolated() // okay
10 |   }

ExtControl.swift:9:5: error: call to main actor-isolated instance method 'implicitlyNonisolated()' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | extension GloballyIsolated {
 2 |   var x: NonSendable { .init() }
 3 |   func implicitlyNonisolated() {}
   |        `- note: calls to instance method 'implicitlyNonisolated()' from outside of its actor context are implicitly asynchronous
 4 | }
 5 | 
   :
 7 |   nonisolated func explicitlyNonisolated() {
 8 |     let _ = x // okay
 9 |     implicitlyNonisolated() // okay
   |     `- error: call to main actor-isolated instance method 'implicitlyNonisolated()' in a synchronous nonisolated context [#ActorIsolatedCall]
10 |   }
11 | }

둘 다 main actor 에 묶인 멤버를 nonisolated 함수에서 쓰려다 막힌다. 멤버마다 nonisolated 를 적는 일이 nonisolated extension 한 곳으로 줄어든다는 것이 이 제안의 편의다.

다만 nonisolated extension 의 범위는 그 extension 안에 쓴 멤버까지다. 타입 본문에 있는 저장 프로퍼티는 건드리지 않는다. 확인하려고 @MainActor class 의 저장 프로퍼티를 nonisolated extension 의 메서드에서 읽어 봤다.

ExtStored.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
@MainActor
final class Model {
  var count = 0
}

nonisolated extension Model {
  func describe() -> String {
    "Model"
  }
  func readCount() -> Int {
    count
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ExtStored.swift:11:5: error: main actor-isolated property 'count' can not be referenced from a nonisolated context
 1 | @MainActor
 2 | final class Model {
 3 |   var count = 0
   |       `- note: property declared here
 4 | }
 5 | 
   :
 9 |   }
10 |   func readCount() -> Int {
11 |     count
   |     `- error: main actor-isolated property 'count' can not be referenced from a nonisolated context
12 |   }
13 | }

describe() 는 문제가 없지만 readCount() 는 막힌다. count 는 타입 본문에서 선언되었고, extension 의 nonisolated 가 그것을 바꾸지 못한다. extension 에 적은 nonisolated 는 그 extension 에 들어 있는 선언에만 적용된다.


nonisolated class, struct, enum

타입 선언에 붙이면 그 타입은 conformance 나 상속에서 오는 isolation 을 추론하지 않는다. 제안서 코드는 nonisolated class K, nonisolated struct S, nonisolated enum E 를 보여 주고, 이 글은 그 뒤에 make() 함수를 붙여 K 와 S 를 만들고 x 를 읽게 했다. 이렇게 붙인 판을 돌렸다.

Types.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
nonisolated class K: GloballyIsolated {
  var x: NonSendable
  init(x: NonSendable) {
    self.x = x // okay, 'x' is non-isolated
  }
}

nonisolated struct S: GloballyIsolated {
  var x: NonSendable
  init(x: NonSendable) {
    self.x = x // okay, 'x' is non-isolated
  }
}

nonisolated enum E: GloballyIsolated {
  func implicitlyNonisolated() {}
  init() {}
}

struct TestEnum {
  nonisolated func call() {
    E().implicitlyNonisolated() // okay
  }
}

nonisolated func make() {
  let k = K(x: NonSendable())
  let s = S(x: NonSendable())
  print(k.x.value, s.x.value)
}

Swift 6 에서 K 와 S 쪽은 진단이 없고, enum E 에서 이런 진단이 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Types.swift:17:11: error: 'self.init' isn't called on all paths before returning from initializer
15 | nonisolated enum E: GloballyIsolated {
16 |   func implicitlyNonisolated() {}
17 |   init() {}
   |           `- error: 'self.init' isn't called on all paths before returning from initializer
18 | }
19 | 

Types.swift:22:9: warning: will never be executed
20 | struct TestEnum {
21 |   nonisolated func call() {
22 |     E().implicitlyNonisolated() // okay
   |     |   `- warning: will never be executed
   |     `- note: a call to a never-returning function
23 |   }
24 | }

이 진단은 isolation 과 상관이 없다. 제안서의 enum E 는 case 가 하나도 없어서, init() {} 가 self 를 만들 방법이 없다. 값을 만들 수 없는 타입에 init 이 있으니 6.4 컴파일러가 “모든 경로에서 self.init 이 불리지 않는다”고 막고, E() 가 돌아오지 않는 호출로 취급되어, 그 뒤에 이어지는 .implicitlyNonisolated() 호출은 실행되지 않는다는 warning 이 붙는다. 6.4 에서 측정하면 이렇다. 이 문제를 걷어내려고 case 를 하나 넣고 init() 이 그 값을 쓰게 고친 판을 돌렸다.

TypesFixed.swift

1
2
3
4
5
6
7
8
9
10
11
nonisolated enum E: GloballyIsolated {
  case only
  func implicitlyNonisolated() {}
  init() { self = .only }
}

struct TestEnum {
  nonisolated func call() {
    E().implicitlyNonisolated() // okay
  }
}

세 모드 모두 진단이 0개다. 이제 nonisolated 를 전부 뺀 대조군이다.

TypesControl.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
class K: GloballyIsolated {
  var x: NonSendable
  init(x: NonSendable) {
    self.x = x // okay, 'x' is non-isolated
  }
}

struct S: GloballyIsolated {
  var x: NonSendable
  init(x: NonSendable) {
    self.x = x // okay, 'x' is non-isolated
  }
}

enum E: GloballyIsolated {
  func implicitlyNonisolated() {}
  init() {}
}

struct TestEnum {
  nonisolated func call() {
    E().implicitlyNonisolated() // okay
  }
}

nonisolated func make() {
  let k = K(x: NonSendable())
  let s = S(x: NonSendable())
  print(k.x.value, s.x.value)
}
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
79
80
81
82
83
84
85
86
87
88
89
90
91
TypesControl.swift:22:9: error: call to main actor-isolated instance method 'implicitlyNonisolated()' in a synchronous nonisolated context [#ActorIsolatedCall]
14 | 
15 | enum E: GloballyIsolated {
16 |   func implicitlyNonisolated() {}
   |        |- note: calls to instance method 'implicitlyNonisolated()' from outside of its actor context are implicitly asynchronous
   |        `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
17 |   init() {}
18 | }
   :
20 | struct TestEnum {
21 |   nonisolated func call() {
22 |     E().implicitlyNonisolated() // okay
   |         `- error: call to main actor-isolated instance method 'implicitlyNonisolated()' in a synchronous nonisolated context [#ActorIsolatedCall]
23 |   }
24 | }

TypesControl.swift:22:5: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
15 | enum E: GloballyIsolated {
16 |   func implicitlyNonisolated() {}
17 |   init() {}
   |   |- note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous
   |   `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
18 | }
19 | 
20 | struct TestEnum {
21 |   nonisolated func call() {
22 |     E().implicitlyNonisolated() // okay
   |     `- error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context [#ActorIsolatedCall]
23 |   }
24 | }

TypesControl.swift:27:11: error: call to main actor-isolated initializer 'init(x:)' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | class K: GloballyIsolated {
 2 |   var x: NonSendable
 3 |   init(x: NonSendable) {
   |   |- note: calls to initializer 'init(x:)' from outside of its actor context are implicitly asynchronous
   |   `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
 4 |     self.x = x // okay, 'x' is non-isolated
 5 |   }
   :
25 | 
26 | nonisolated func make() {
27 |   let k = K(x: NonSendable())
   |           `- error: call to main actor-isolated initializer 'init(x:)' in a synchronous nonisolated context [#ActorIsolatedCall]
28 |   let s = S(x: NonSendable())
29 |   print(k.x.value, s.x.value)

TypesControl.swift:28:11: error: call to main actor-isolated initializer 'init(x:)' in a synchronous nonisolated context [#ActorIsolatedCall]
 8 | struct S: GloballyIsolated {
 9 |   var x: NonSendable
10 |   init(x: NonSendable) {
   |   |- note: calls to initializer 'init(x:)' from outside of its actor context are implicitly asynchronous
   |   `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
11 |     self.x = x // okay, 'x' is non-isolated
12 |   }
   :
26 | nonisolated func make() {
27 |   let k = K(x: NonSendable())
28 |   let s = S(x: NonSendable())
   |           `- error: call to main actor-isolated initializer 'init(x:)' in a synchronous nonisolated context [#ActorIsolatedCall]
29 |   print(k.x.value, s.x.value)
30 | }

TypesControl.swift:29:11: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
 1 | class K: GloballyIsolated {
 2 |   var x: NonSendable
   |       `- note: property declared here
 3 |   init(x: NonSendable) {
 4 |     self.x = x // okay, 'x' is non-isolated
   :
27 |   let k = K(x: NonSendable())
28 |   let s = S(x: NonSendable())
29 |   print(k.x.value, s.x.value)
   |           `- error: main actor-isolated property 'x' can not be referenced from a nonisolated context
30 | }
31 | 

TypesControl.swift:29:22: error: main actor-isolated property 'x' can not be referenced from a nonisolated context
 7 | 
 8 | struct S: GloballyIsolated {
 9 |   var x: NonSendable
   |       `- note: property declared here
10 |   init(x: NonSendable) {
11 |     self.x = x // okay, 'x' is non-isolated
   :
27 |   let k = K(x: NonSendable())
28 |   let s = S(x: NonSendable())
29 |   print(k.x.value, s.x.value)
   |                      `- error: main actor-isolated property 'x' can not be referenced from a nonisolated context
30 | }
31 | 

error 가 여섯 개 나온다. 첫째 22:9 는 implicitlyNonisolated() 가 main actor 에 묶였다는 것이고, 둘째 22:5 는 E() 의 init 이 main actor 에 묶였다는 것이다. 나머지는 make() 에서 K 와 S 의 init 을 부르는 27:11, 28:11, 그리고 x 를 읽는 29:11, 29:22 다. 정리하면 class, struct, enum 모두에서 멤버와 init 과 저장 프로퍼티까지 main actor 로 추론되던 것이 nonisolated 한 단어로 모두 풀린다.


중첩 타입의 재추론

타입에 nonisolated 를 붙이면 그 안에 선언한 중첩 타입도 nonisolated 가 될까. 제안서는 아니라고 하고, @MainActor 가 중첩 타입에 퍼지지 않는 것과 같은 규칙이라고 설명한다. 코드를 돌려 본다.

Nested.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
nonisolated struct S: GloballyIsolated {
  var value: NonSendable // 'value' is not isolated
  struct Nested: GloballyIsolated { // 'Nested' is still @MainActor-isolated
    func work() {}
  }
  struct Plain {
    func work() {}
  }
}

@MainActor struct M {
  var value: NonSendable // globally-isolated
  struct Nested { // 'Nested' is not @MainActor-isolated
    func work() {}
  }
}

nonisolated func use() {
  S.Nested().work()
  S.Plain().work()
  M.Nested().work()
}

Swift 6 와 complete 에서는 error 가 하나 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Nested.swift:19:14: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 2 |   var value: NonSendable // 'value' is not isolated
 3 |   struct Nested: GloballyIsolated { // 'Nested' is still @MainActor-isolated
 4 |     func work() {}
   |          |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
   |          `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
 5 |   }
 6 |   struct Plain {
   :
17 | 
18 | nonisolated func use() {
19 |   S.Nested().work()
   |              `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
20 |   S.Plain().work()
21 |   M.Nested().work()

S.Nested 만 걸린다. S 는 nonisolated 지만 그 안의 Nested 는 자기 선언의 GloballyIsolated 에서 main actor 를 다시 추론하고, note 도 그 conformance 를 가리킨다. S.Plain 은 따르는 protocol 이 없어서 추론할 것이 없고, M.Nested 는 바깥이 @MainActor 지만 중첩 타입이 그것을 이어받지 않아서 둘 다 진단이 없다. Swift 5 모드에서는 같은 19:14 에 19:5: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context 가 하나 더 붙는다. Nested 의 암시적 init 이 Swift 5 모드에서는 main actor 로 취급된다는 측정이고, Swift 6 와 complete 에서는 init 이 nonisolated 로 취급되어 이 error 가 없다.

nonisolated 는 바깥 타입의 멤버에만 퍼지고 중첩 타입의 추론은 막지 않는다. 중첩 타입까지 끊으려면 중첩 타입에도 nonisolated 를 적어야 한다.


타입과 extension 의 conformance 가 만날 때

피치 xwu #3 은 이런 질문을 했다. nonisolated struct S 에 extension S: GloballyIsolatedProtocol 을 쓰면 어느 규칙이 이기는가. 타입에 nonisolated 가 있고, extension 의 conformance 가 global actor 를 추론시키려 하는 상황이다. 피치 스레드에서 이 질문에 대한 답글은 없었고(simanerush #4 는 “제안서를 고쳤다”는 한 줄이다), 6.4 측정으로 답한다. 위 우회법 1 의 XwuWitnessControl.swift 에서 struct S {} 의 nonisolated 만 추가한 판이다.

XwuWitness.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@MainActor
protocol P {
  func requirement()
}

nonisolated struct S {}

extension S: P {
  func requirement() {}
  func helper() {}
}

nonisolated func use(s: S) {
  s.requirement()
  s.helper()
}

세 모드 모두 진단이 0개다. 같은 코드에서 nonisolated 만 뺀 대조군은 위 “extension 으로 우회하기” 의 XwuWitnessControl.swift 이고, 14:5 error 가 났다. 타입 선언의 nonisolated 가 extension 에서 선언한 conformance 의 witness 까지 main actor 로 추론되는 것을 막는다.


실행 위치

nonisolated 가 컴파일 오류만 바꾸는지, 실제로 코드가 도는 스레드까지 바꾸는지 확인하려고 실행해 봤다. Task.detached 안에서 isolation 이 있는 타입과 없는 타입의 메서드를 부르고, Thread.isMainThread 로 어디서 도는지 찍는다.

Where.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Foundation

struct Isolated: GloballyIsolated {
  func whereAmI() -> String { Thread.isMainThread ? "main" : "other" }
}

nonisolated struct Cut: GloballyIsolated {
  func whereAmI() -> String { Thread.isMainThread ? "main" : "other" }
}

@main
struct App {
  static func main() async {
    await Task.detached {
      let isolated = Isolated()
      let cut = Cut()
      print("Isolated.whereAmI():", await isolated.whereAmI())
      print("Cut.whereAmI():     ", cut.whereAmI())
    }.value
  }
}

Thread.isMainThread 와 Task.detached 로 실행 위치 찍기

Thread.isMainThread 는 지금 코드가 main thread 에서 돌고 있으면 true 를 주는 Foundation 의 프로퍼티다. Task.detached 는 만든 곳의 isolation 을 이어받지 않는 독립 Task 를 만들고, 이 코드에서는 main actor 밖의 스레드에서 시작한다. .value 는 그 Task 가 끝나기를 기다린다. @main 은 프로그램의 시작점을 이 타입의 static func main() 으로 정하는 속성이다. await isolated.whereAmI() 는 main actor 로 건너가서 실행해야 하니 await 가 필요하고, cut.whereAmI() 는 await 없이 부른다.

두 번 돌려도 결과가 같았다.

1
2
Isolated.whereAmI(): main
Cut.whereAmI():      other

struct Isolated: GloballyIsolated 는 main actor 에 묶여 있어서 await 로 건너가 main 에서 돈다. nonisolated struct Cut: GloballyIsolated 는 await 없이 부르는 쪽 스레드에서 그대로 돈다. 그래서 nonisolated 는 컴파일러가 보는 표시에서 그치지 않고 실제 실행 위치를 바꾼다. 이 코드를 처음 쓸 때는 let isolated = await Isolated() 로 썼다. 그랬더니 15:22: warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker] 가 나왔다. 저장 프로퍼티가 없는 struct 의 암시적 init() 은 main actor 가 아니라서 await 가 필요 없다는 뜻이고, 위 코드의 Isolated() 에는 await 가 없다.


non-Sendable 타입의 저장 프로퍼티

저장 프로퍼티 쪽은 두 가지 확장이 있다. 먼저 non-Sendable 타입의 저장 프로퍼티다. 제안서 코드에 nonisolated 가 있는 x 와 없는 y 를 두고 nonisolated 함수에서 둘 다 써 봤다. 샘플에 같이 둔 @MainActor class MainClass 는 대비용이다. use 는 이 클래스를 쓰지 않지만, 같은 y 를 MainClass 에서 읽어 보면 main actor-isolated property 'y' can not be referenced from a nonisolated context error 가 난다. 클래스가 @MainActor 이면 non-Sendable 저장 프로퍼티도 main actor 에 묶인다는 측정이다.

StoredNonSendable.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyClass {
  nonisolated var x: NonSendable = NonSendable() // okay
  var y: NonSendable = NonSendable()
}

@MainActor
class MainClass {
  var y: NonSendable = NonSendable()
}

nonisolated func use(c: MyClass) {
  c.x.value += 1
  c.y.value += 1
}

세 모드 모두 진단이 0개다. nonisolated var x 는 물론이고 nonisolated 가 없는 y 도 막히지 않는다. non-Sendable 타입의 저장 프로퍼티는 원래 nonisolated 로 취급되고, 이 제안은 그것을 철자로 적을 수 있게 했을 뿐이다. 그래서 x 와 y 의 동작 차이가 없다. 피치에서 이 부분이 여러 번 오간 이유가 이것이다. j-f1 #8 이 “non-Sendable 클래스의 프로퍼티에 nonisolated 를 적는 것과 적지 않는 것의 동작 차이가 무엇인가” 를 물었는데, 위 측정이 그 답이다. 차이는 코드가 아니라 철자에 있다.

오간 질문은 이렇다. donny_wals #5 는 non-Sendable 타입이 여러 isolation domain 에서 접근되는 것이 막히지 않느냐고, 그리고 “base instance” 가 무엇이냐고 물었다. hborla #6 이 답했다. non-Sendable 값은 한 번에 한 isolation domain 에서만 접근될 수 있고, 어느 한 domain 에서 쓰는 것은 상관없다. nonisolated 는 self 를 참조하는 domain 의 개수를 바꾸지 않는다는 것이다. donny_wals #7 은 코드 예제를 요청했고, 제안서의 이 문단이 그 논의를 반영해서 고쳐졌다.


Sendable 값 타입의 var 저장 프로퍼티

둘째는 SE-0434 글이 열어 준 규칙의 확장이다. SE-0434 는 global actor 에 묶인 값 타입의 var 저장 프로퍼티가 Sendable 이면 nonisolated 로 쓰게 했다. 이 제안은 그 규칙을 global actor 에 묶이지 않은 것까지 포함해 모든 Sendable 값 타입으로 넓힌다. 그래서 @MainActor 요구 사항을 구현하는 Sendable 값 타입의 Sendable var 저장 프로퍼티는 같은 모듈 안에서 nonisolated 로 추론된다. 제안서 코드에 print(x) 를 붙여 돌렸다.

ValueVar.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protocol P {
  @MainActor var y: Int { get }
}

struct S: P {
  var y: Int // 'nonisolated' is inferred within the module
}

struct F {
  nonisolated func getS(_ s: S) {
    let x = s.y // okay
    print(x)
  }
}

세 모드 모두 진단이 0개다. y 는 @MainActor 요구 사항을 구현하지만 Int 가 Sendable 이고 S 가 값 타입이라서, 같은 모듈 안에서는 nonisolated 로 추론되고 getS 에서 동기로 읽을 수 있다. 이 추론이 일어나려면 프로퍼티 타입이 Sendable 이어야 한다. y 의 타입을 NonSendable 로 바꿔서 확인했다.

ValueVarNonSendable.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protocol P {
  @MainActor var y: NonSendable { get }
}

struct S: P {
  var y: NonSendable
}

struct F {
  nonisolated func getS(_ s: S) {
    let x = s.y
    print(x)
  }
}

Swift 6 에서는 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ValueVarNonSendable.swift:5:8: error: memberwise initializer for 'S' cannot be both nonisolated and main actor-isolated
 3 | }
 4 | 
 5 | struct S: P {
   |        `- error: memberwise initializer for 'S' cannot be both nonisolated and main actor-isolated
 6 |   var y: NonSendable
   |       `- note: initializer for property 'y' is main actor-isolated
 7 | }
 8 | 

ValueVarNonSendable.swift:11:15: error: main actor-isolated property 'y' can not be referenced from a nonisolated context
 4 | 
 5 | struct S: P {
 6 |   var y: NonSendable
   |       `- note: property declared here
 7 | }
 8 | 
 9 | struct F {
10 |   nonisolated func getS(_ s: S) {
11 |     let x = s.y
   |               `- error: main actor-isolated property 'y' can not be referenced from a nonisolated context
12 |     print(x)
13 |   }

Swift 5 모드는 두 번째 error(11:15)만 낸다. complete 는 첫째가 5:8: warning: memberwise initializer for 'S' cannot be both nonisolated and main actor-isolated; this is an error in the Swift 6 language mode 로 내려가고 둘째는 그대로 error 다. 프로퍼티의 타입이 Sendable 이 아니면 추론이 일어나지 않는다. y 는 main actor 에 묶이고 getS 에서 읽으면 막힌다. memberwise initializer 가 y 의 isolation 과 충돌한다는 첫 번째 error 는 이 상황에서 따라붙는 진단이다.

모듈 경계

추론은 같은 모듈 안에서만 일어난다. 다른 모듈은 y 가 어떻게 선언되었는지 구현을 모르기 때문이다. 모듈을 둘로 나눠서 돌렸다.

ModA.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
public protocol P {
  @MainActor var y: Int { get }
}

public struct Implicit: P {
  public var y: Int // globally-isolated outside of the module
  public init(y: Int) { self.y = y }
}

public struct Explicit: P {
  public nonisolated var y: Int // 'y' is explicitly non-isolated
  public init(y: Int) { self.y = y }
}

ModB.swift 는 import A 로 위 모듈을 쓴다.

ModB.swift

1
2
3
4
5
6
7
8
9
import A

struct F {
  nonisolated func get(_ i: Implicit, _ e: Explicit) {
    let x = i.y
    let z = e.y
    print(x, z)
  }
}

모듈 A 를 먼저 빌드하고 B 가 그것을 import 하게 돌렸다.

1
2
xcrun swiftc -emit-module -module-name A -parse-as-library -swift-version 6 ModA.swift -emit-module-path A.swiftmodule
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -swift-version 6 -I . ModB.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ModB.swift:5:15: error: main actor-isolated property 'y' can not be referenced from a nonisolated context
 3 | struct F {
 4 |   nonisolated func get(_ i: Implicit, _ e: Explicit) {
 5 |     let x = i.y
   |               `- error: main actor-isolated property 'y' can not be referenced from a nonisolated context
 6 |     let z = e.y
 7 |     print(x, z)

ModA.swift:6:14: note: property declared here
 4 | 
 5 | public struct Implicit: P {
 6 |   public var y: Int // globally-isolated outside of the module
   |              `- note: property declared here
 7 |   public init(y: Int) { self.y = y }
 8 | }

Implicit.y 를 다른 모듈에서 읽으려는 5:15 가 막힌다. Explicit.y 를 읽는 6:15 는 진단이 없다. 모듈 밖에서는 nonisolated 를 직접 적어야 동기로 읽을 수 있다. 같은 두 타입을 같은 모듈 안에서 쓰면 어떨까. ModAInside.swift 를 ModA.swift 와 한 모듈로 묶어 돌렸다.

ModAInside.swift

1
2
3
4
5
6
7
struct F {
  nonisolated func get(_ i: Implicit, _ e: Explicit) {
    let x = i.y
    let z = e.y
    print(x, z)
  }
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 ModA.swift ModAInside.swift

진단이 0개다. 같은 모듈 안에서는 Implicit.y 도 Explicit.y 도 동기로 읽힌다.

@MainActor 요구 사항을 구현하는 Sendable 값 타입의 var y 는 같은 모듈 안에서는 nonisolated 로 추론되어 동기로 읽히고, 다른 모듈에서는 nonisolated 를 직접 적어야 동기로 읽힌다

이 구분은 피치에서 여러 질문을 낳았다. ktoso #2 는 제안서 초안의 해당 항목이 모듈 안과 밖의 이야기를 섞어서 헷갈린다고 했고, “synchronized access” 라는 표현이 거꾸로 쓰인 것 같다고 짚었다. 최종 제안서의 “Therefore, synchronous access of y is okay.” 라는 문장은 그 지적 뒤에 고쳐진 것이다. xwu #3 은 이것이 명시를 요구하는 것인지 추론인지, Sendable 값을 감싸는 타입을 만들 때 그 멤버마다 nonisolated 를 전방위로 붙여야 하는지, 그리고 성능과 @frozen 으로 인한 ABI 영향을 물었다. 모듈 안에서는 추론이 되고 모듈 밖에서는 명시해야 한다는 위 측정이 앞의 두 질문의 답에 가깝다. xwu #9 는 Int 의 _value 는 nightly 의 complete 검사에서도 이미 허용되지 않느냐며 제안서의 설명이 이해되지 않는다고 했고, 그 글에는 답글이 없다.


적을 수 없는 자리

nonisolated 를 적을 수 없거나 적어도 소용없는 자리가 있다. 제안서 Restrictions 의 코드를 하나씩 돌렸다. 피치에서 ktoso #2 는 제약마다 이유를 한 문장씩 붙이자고 했다. 제안서가 학습 자료로도 읽히니 규칙만 던지지 말고 이유를 설명하자는 것이었다. 이 글도 그 방식으로 각 측정에 해석을 붙인다.

@MainActor 와 nonisolated 를 함께 쓰기

Restrict.swift

1
2
@MainActor
nonisolated struct Conflict {}

세 모드 모두 같은 error 가 나온다.

1
2
3
4
5
Restrict.swift:2:20: error: struct 'Conflict' has multiple actor-isolation attributes (@MainActor and 'nonisolated')
1 | @MainActor
2 | nonisolated struct Conflict {}
  |                    `- error: struct 'Conflict' has multiple actor-isolation attributes (@MainActor and 'nonisolated')
3 | 

한 선언에 isolation 을 두 번 적을 수 없다. 6.4 의 문구는 multiple actor-isolation attributes (@MainActor and 'nonisolated') 다.

nonisolated let 에 non-Sendable 타입

RestrictLet.swift

1
2
3
4
@MainActor
struct InvalidStruct /* implicitly Sendable */ {
  nonisolated let x: NonSendable
}

Swift 5 모드는 진단이 0개다. complete 는 3:3: warning: 'nonisolated' can not be applied to variable with non-'Sendable' type 'NonSendable'; this is an error in the Swift 6 language mode 를 낸다. Swift 6 에서는 error 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
RestrictLet.swift:3:3: error: 'nonisolated' can not be applied to variable with non-'Sendable' type 'NonSendable'
1 | @MainActor
2 | struct InvalidStruct /* implicitly Sendable */ {
3 |   nonisolated let x: NonSendable
  |   `- error: 'nonisolated' can not be applied to variable with non-'Sendable' type 'NonSendable'
4 | }
5 | 

Common.swift:1:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
1 | final class NonSendable { var value = 0 }
  |             `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 | 
3 | @MainActor

let 저장 프로퍼티를 nonisolated 로 쓰려면 그 타입이 Sendable 이어야 한다. isolation 밖에서 다른 곳으로 퍼질 수 있는 값이니, 안전하게 퍼지는 타입이어야 한다는 것이다.

변경 가능한 저장 프로퍼티

RestrictVar.swift

1
2
3
4
@MainActor
final class InvalidClass /* implicitly Sendable */ {
  nonisolated var test: Int = 1
}

세 모드 모두 같은 error 가 나온다.

1
2
3
4
5
6
7
8
RestrictVar.swift:3:3: error: 'nonisolated' cannot be applied to mutable stored properties
1 | @MainActor
2 | final class InvalidClass /* implicitly Sendable */ {
3 |   nonisolated var test: Int = 1
  |   |               `- note: convert 'test' to a 'let' constant or consider declaring it 'nonisolated(unsafe)' if manually managing concurrency safety
  |   `- error: 'nonisolated' cannot be applied to mutable stored properties
4 | }
5 | 

Sendable class 에서 mutable 저장 프로퍼티는 nonisolated 가 될 수 없다. 값 타입은 isolation domain 마다 독립된 복사본을 가지므로 var 에 대입해도 다른 쪽 복사본에 영향이 없지만, class 는 참조라서 한 인스턴스를 여러 곳에서 쓸 수 있어 var 가 동시에 변경될 수 있다. note 가 마지막 길을 알려 준다. let 으로 바꾸거나 nonisolated(unsafe) 를 쓰라는 것이다. ktoso #2 는 사람들이 이 탈출구를 잘 모른다며 Restrictions 에 nonisolated(unsafe) 를 적어 두자고 했다. nonisolated(unsafe) 로 바꾼 판을 돌렸다.

RestrictUnsafe.swift

1
2
3
4
5
6
7
8
@MainActor
final class EscapeHatch {
  nonisolated(unsafe) var test: Int = 1
}

nonisolated func use(e: EscapeHatch) {
  e.test += 1
}

진단이 0개다. 컴파일은 통과하지만 이것은 검사를 끄는 것이다. 접근을 직접 동기화하는 경우에만 쓴다.

actor, typealias, 전역 변수

OtherDecls.swift

1
2
3
4
nonisolated actor A {}
nonisolated typealias Alias = Int
nonisolated var globalValue = 0
nonisolated let globalConstant = 0

Swift 6 에서 이렇게 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
OtherDecls.swift:1:1: error: 'nonisolated' modifier cannot be applied to this declaration
1 | nonisolated actor A {}
  | `- error: 'nonisolated' modifier cannot be applied to this declaration
2 | nonisolated typealias Alias = Int
3 | nonisolated var globalValue = 0

OtherDecls.swift:2:1: error: 'nonisolated' modifier cannot be applied to this declaration
1 | nonisolated actor A {}
2 | nonisolated typealias Alias = Int
  | `- error: 'nonisolated' modifier cannot be applied to this declaration
3 | nonisolated var globalValue = 0
4 | nonisolated let globalConstant = 0

OtherDecls.swift:3:17: error: var 'globalValue' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
1 | nonisolated actor A {}
2 | nonisolated typealias Alias = Int
3 | nonisolated var globalValue = 0
  |                 |- error: var 'globalValue' is not concurrency-safe because it is nonisolated global shared mutable state [#MutableGlobalVariable]
  |                 |- note: convert 'globalValue' to a 'let' constant to make 'Sendable' shared state immutable
  |                 |- note: add '@MainActor' to make var 'globalValue' part of global actor 'MainActor'
  |                 `- note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
4 | nonisolated let globalConstant = 0
5 | 

OtherDecls.swift:3:1: error: 'nonisolated' cannot be applied to mutable stored properties
1 | nonisolated actor A {}
2 | nonisolated typealias Alias = Int
3 | nonisolated var globalValue = 0
  | |               `- note: convert 'globalValue' to a 'let' constant or consider declaring it 'nonisolated(unsafe)' if manually managing concurrency safety
  | `- error: 'nonisolated' cannot be applied to mutable stored properties
4 | nonisolated let globalConstant = 0
5 | 

nonisolated actor 와 nonisolated typealias 는 선언 자체가 받지 않는다. actor 는 이미 자기 자신이 isolation 의 단위라서 nonisolated 를 붙일 의미가 없다. 전역 var 는 두 줄의 error 로 막히고, let 은 오류가 없다. 첫 error 는 SE-0412 글이 다룬 전역 mutable 상태 검사이고, 둘째는 mutable 저장 프로퍼티 제약이다. complete 에서는 첫 error 가 warning 으로 내려가고, Swift 5 에서는 아예 나오지 않는다.

nonisolated class 가 subclass 일 때

SubclassNonisolated.swift

1
2
3
4
5
6
7
8
9
10
11
12
@MainActor
class MainBase {}

nonisolated class Sub: MainBase {
  func work() {}
}

class Base: GloballyIsolated {}

nonisolated class Sub2: Base {
  func work() {}
}

Swift 5 와 complete 에서는 4:19 와 10:19 가 non-final class 'Sub' cannot conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode 라는 warning 으로 나온다. Swift 6 의 error 는 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SubclassNonisolated.swift:4:19: error: non-final class 'Sub' cannot conform to the 'Sendable' protocol
 2 | class MainBase {}
 3 | 
 4 | nonisolated class Sub: MainBase {
   |                   `- error: non-final class 'Sub' cannot conform to the 'Sendable' protocol
 5 |   func work() {}
 6 | }

SubclassNonisolated.swift:10:19: error: non-final class 'Sub2' cannot conform to the 'Sendable' protocol
 8 | class Base: GloballyIsolated {}
 9 | 
10 | nonisolated class Sub2: Base {
   |                   `- error: non-final class 'Sub2' cannot conform to the 'Sendable' protocol
11 |   func work() {}
12 | }

global actor 에 묶인 class 는 암시적으로 Sendable 이다. subclass 는 상속받은 Sendable conformance 를 그대로 지니는데, nonisolated 가 되어 isolation 이 없어진 non-final class 는 그 conformance 를 만족할 수 없어 error 가 난다. 사용처가 없어도 선언에서 난다. 6.4 가 낸 문구는 이것뿐이고, @MainActor class 를 상속한 경우와 conformance 로 추론된 class 를 상속한 경우 모두 같다.

정리

자리6.4 측정
@MainActor nonisolated structerror: multiple actor-isolation attributes
Sendable 타입 안의 non-Sendable letSwift 5 진단 없음, complete warning, Swift 6 error
Sendable class 의 nonisolated var세 모드 error (note 가 let 이나 nonisolated(unsafe) 를 안내)
nonisolated(unsafe) var진단 없음 (검사를 끈 것)
nonisolated actor, nonisolated typealias세 모드 error: cannot be applied to this declaration
nonisolated var 전역 변수error 둘 (Swift 6 기준. Swift 5 는 mutable 저장 프로퍼티 error 하나)
nonisolated let 전역 상수진단 없음
nonisolated class subclassSwift 5 와 complete warning, Swift 6 error: non-final class cannot conform to Sendable

기대 효과

global actor 는 protocol conformance 와 protocol refinement 와 상속을 따라 타입으로 흘러 들어오는데, nonisolated 를 적으면 그 선언에서 흐름이 끊기지만 중첩 타입은 자기 conformance 에서 다시 추론한다

그림 1 은 위의 측정을 한 장으로 줄인 것이다. 위쪽이 Infer.swift 의 세 흐름이고, 아래쪽이 Proto.swift 의 끊김과 Nested.swift 의 예외다. 이 제안이 가져오는 것은 네 가지다.

  1. 의도를 선언 한 곳에 적는다. 멤버마다 nonisolated 를 적거나 conformance 를 extension 으로 옮기던 것이 선언 앞 한 단어로 모인다. nonisolated extension 은 그 자체로 한 곳이고, 타입에 붙이면 타입 전체가 대상이다.
  2. 우회 trick 이 사라진다. FakeGlobalActor 같은 가짜 global actor 와 가짜 executor 가 nonisolated protocol 한 줄로 바뀐다. ktoso #2 가 말한 대로 이 trick 은 제대로 된 철자로 대체되었다.
  3. conformance 사슬이 길어도 결과를 예측할 수 있다. 사슬 중간에 nonisolated 가 있으면 거기서 끊긴다는 한 줄로 설명된다.
  4. 타입을 nonisolated 로 두고 동기로 쓰는 라이브러리 타입을 만들기 쉬워진다. 6.4 의 Where.swift 에서 본 것처럼 nonisolated struct Cut 은 await 없이 부르는 쪽 스레드에서 돈다.

다른 선택지는 왜 안 됐나

제안서 Alternatives 는 선택지 하나를 다룬다. 타입 선언이 아니라 conformance 목록에 nonisolated 를 적는 철자다.


conformance 목록에 적는 방법

struct S: nonisolated GloballyIsolated {} 처럼 따르는 protocol 하나하나에 nonisolated 를 적는 방법이다. 6.4 에서 이 문법을 돌려 봤다.

ConformanceList.swift

1
struct S: nonisolated GloballyIsolated {}

세 모드 모두 진단이 0개다. 문법으로는 받아들여진다. 그러면 추론도 끊을까. S 에 work() 를 넣고 nonisolated 함수에서 불렀다.

ConformanceListUse.swift

1
2
3
4
5
6
7
struct S: nonisolated GloballyIsolated {
  func work() {}
}

nonisolated func use(s: S) {
  s.work()
}

세 모드 모두 이렇게 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
ConformanceListUse.swift:6:5: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
1 | struct S: nonisolated GloballyIsolated {
2 |   func work() {}
  |        |- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
  |        `- note: main actor isolation inferred from conformance to protocol 'GloballyIsolated'
3 | }
4 | 
5 | nonisolated func use(s: S) {
6 |   s.work()
  |     `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
7 | }
8 | 

문법은 통과하지만 S 의 work() 는 여전히 main actor 에 묶이고 note 도 GloballyIsolated 를 출처로 가리킨다. 이 철자는 이 제안이 쓰는 방식으로는 global actor 추론을 끊지 못한다. 이 철자는 이후 SE-0470 에서 conformance 자체의 isolation 을 적는 자리로 쓰이고, 이 글에서 다루는 cut-off 와는 다른 기능이다.


앞으로의 방향

이 철자는 이후 SE-0466 의 모듈 기본 isolation 과 함께 쓸 때 쓸모가 더 커진다.


default actor isolation 과 함께

SE-0466 은 모듈 단위로 기본 isolation 을 MainActor 로 바꾸는 옵션을 만든다. 이 설정에서는 선언이 모두 main actor 가 기본이 되어서, 거기서 빠져나오는 철자가 필요하다. 이 제안의 nonisolated struct 와 nonisolated extension 이 그 자리다. -default-isolation MainActor 를 주고 돌렸다.

DefaultIso.swift

1
2
3
4
5
6
7
8
9
10
11
12
struct Model {
  func work() {}
}

nonisolated struct Plain {
  func work() {}
}

nonisolated func use(m: Model, p: Plain) {
  m.work()
  p.work()
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -default-isolation MainActor Common.swift DefaultIso.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
DefaultIso.swift:10:5: error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
 1 | struct Model {
 2 |   func work() {}
   |        `- note: calls to instance method 'work()' from outside of its actor context are implicitly asynchronous
 3 | }
 4 | 
   :
 8 | 
 9 | nonisolated func use(m: Model, p: Plain) {
10 |   m.work()
   |     `- error: call to main actor-isolated instance method 'work()' in a synchronous nonisolated context [#ActorIsolatedCall]
11 |   p.work()
12 | }

struct Model 은 nonisolated 가 없어서 main actor 에 묶이고, m.work() 가 막힌다. note 에는 추론 출처가 없다. protocol 이나 상속에서 온 것이 아니라 모듈 기본값이 정한 isolation 이기 때문이다. nonisolated struct Plain 은 진단이 없다.


Swift 6 모드와 마이그레이션

소스 호환성과 ABI 에 미치는 영향은 제안서가 없다고 정리한다. 이 제안은 기존 코드의 의미를 바꾸지 않고, 새로 쓸 수 있는 철자를 더한다. 이 글의 측정은 대부분 세 모드의 결과가 같았다. 달라지는 곳은 두 갈래다. RestrictLet, Adoption, FakeActor 는 Swift 5 에서 진단이 없고 complete 에서 warning, Swift 6 에서 error 가 된다. ValueVarNonSendable 의 5:8 진단(memberwise initializer)도 같은 갈래다. SubclassNonisolated 는 Swift 5 부터 warning 이다. Nested 는 Swift 5 에서만 19:5 error 가 하나 더 나오고, OtherDecls 의 전역 변수 진단은 모드마다 개수가 다르다.

제안서가 Implications on adoption 에서 짚는 것은 이미 공개한 타입에 nonisolated 를 붙이는 경우다. global actor 에 묶인 class 는 암시적으로 Sendable 이다. nonisolated 를 붙이면 그 암시적 Sendable 이 사라져서, 그 타입을 Sendable 이 필요한 자리에 쓰던 호출 쪽 소스가 깨질 수 있다. 같은 코드에서 C 와 nonisolated D 를 some Sendable 에 넘겨 봤다.

Adoption.swift

1
2
3
4
5
6
7
8
9
10
func send(_ value: some Sendable) {}

class C: GloballyIsolated {}
nonisolated class D: GloballyIsolated {}

@MainActor
func use() {
  send(C())
  send(D())
}

Swift 5 는 진단이 없고, complete 는 9:3: warning: type 'D' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode 를 낸다. Swift 6 은 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
Adoption.swift:9:3: error: type 'D' does not conform to the 'Sendable' protocol
 2 | 
 3 | class C: GloballyIsolated {}
 4 | nonisolated class D: GloballyIsolated {}
   |                   `- note: class 'D' does not conform to the 'Sendable' protocol
 5 | 
 6 | @MainActor
 7 | func use() {
 8 |   send(C())
 9 |   send(D())
   |   `- error: type 'D' does not conform to the 'Sendable' protocol
10 | }
11 | 

send(C()) 는 문제가 없고 send(D()) 는 막힌다. 라이브러리 작성자라면 공개한 class 에 nonisolated 를 붙이는 일이 소스 호환성에 영향을 줄 수 있다는 점을 알고 있어야 한다. 마이그레이션 측면에서 해 볼 만한 일은 둘이다. 하나는 FakeGlobalActor 같은 우회를 쓰던 코드를 nonisolated protocol 로 바꾸는 것이다. 다른 하나는 멤버마다 붙인 nonisolated 를 nonisolated extension 한 곳으로 모으는 것이다.


정리

  • nonisolated 가 protocol, extension, class, struct, enum 선언에 붙을 수 있게 되었고, 붙이면 conformance, refinement, 상속에서 오는 global actor 추론이 그 선언에서 끊긴다.
  • 끊기는 범위는 그 선언의 멤버까지다. nonisolated extension 은 타입 본문의 저장 프로퍼티를 바꾸지 못하고, 중첩 타입은 자기 conformance 에서 다시 추론한다.
  • 타입의 nonisolated 는 extension 에서 선언한 conformance 의 witness 추론보다 먼저 적용된다.
  • Task.detached 안에서 await 없이 부른 nonisolated struct 의 메서드는 main 이 아닌 스레드에서 돌았다.
  • 저장 프로퍼티는 non-Sendable 타입에 철자를 허용하고(동작 차이는 없다), Sendable 값 타입의 var 에는 같은 모듈 안에서 nonisolated 를 추론한다. 다른 모듈에서는 직접 적어야 동기로 읽힌다.
  • 적을 수 없는 자리가 있고(@MainActor 와 함께, Sendable 타입 안의 non-Sendable let, Sendable class 의 mutable 저장 프로퍼티, actor, typealias), 이미 공개한 class 에 붙이면 암시적 Sendable 이 사라진다.
  • 리뷰 스레드에는 의견 글이 없었고 논의는 피치에서 끝났다. 수락 공지는 SE-0434 와 같은 정신의 사용성 개선이라고 설명한다.

관련 글


참고자료

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