# Why no compiler error for this Swift Concurrency/Combine code?

**URL:** <https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897>\
**Category:** Using Swift\
**Tags:** concurrency, combine\
**Created:** [November 8, 2024, 9:20am UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897 "2024-11-08T09:20:16Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![mjholgate](https://avatars.discourse-cdn.com/v4/letter/m/df788c/32.png) [@mjholgate](https://forums.swift.org/u/mjholgate)\
**Post date:** [November 8, 2024, 9:20am UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/1 "2024-11-08T09:20:16Z")

</div>

Hi there,

The sample code below compiles fine in both Swift 5 and Swift 6 language modes with no errors or warnings. I would expect it to fail with an error or warning because the `sink` closure attempts to call the `receiveValue` method which as a global actor isolated method should not be possible from a synchronous, non-isolated context (which has also been requested to be dynamically called on the main queue).

If I run this code in Swift 5 with the thread sanitiser, I get an error as expected since there is a race reading/writing `copyValue` from multiple threads.

If I run this code in Swift 6 (even without the thread sanitiser), I get a runtime exception: "Incorrect actor executor assumption".

All of that makes sense, but why does is the compiler not able to determine this statically? I tried building my own code which receives a closure similarly to Combine, and in this context, the issue is correctly flagged at compile time with an error (or warning in Swift 5). To get it to build, I had to make the closure `@Sendable`.

I checked the Combine API and I can't see any sign of the `@Sendable` annotation on the sink closure, nor can I see any instances of `@unchecked Sendable` or `@preconcurrency` which might be an "escape hatch".

So this leaves the question about what is special about Combine? Is there a special hack in the compiler to avoid breaking existing pre-concurrency code?

Thanks  
Matt.

```swift
import SwiftUI
import Foundation
import Combine

@globalActor actor MyActor {
    static var shared: some Actor = MyActor()
}

@MyActor
class MyClass {
    var sub: AnyCancellable?
    var value = CurrentValueSubject<Int, Never>(1)
    var copyValue: Int = 0

    nonisolated init() {
        Task {
            await setup()
        }
    }

    func setup() {
        sub = value
            .receive(on: DispatchQueue.main)
            .sink {
                self.receiveValue(value: $0)
            }
    }

    func receiveValue(value: Int) {
        print("receiveValue thread = \(Thread.current)")
        copyValue = value
    }

    func set(value: Int) {
        print("set thread = \(Thread.current)")
        self.value.send(value)
        for _ in 0..<1000 {
            print(copyValue)
        }
    }

}

struct ContentView: View {
    @State var obj = MyClass()
    var body: some View {
        VStack {
            Button("Go") {
                Task {
                    await obj.set(value: await obj.copyValue + 1)
                    print("Value = \(await obj.copyValue)")
                }
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

```

---

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [November 8, 2024, 1:31pm UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/2 "2024-11-08T13:31:03Z")

</div>

Looks like an issue in diagnostics to me. Worth filing an issue on a GitHub.

---

<div class="post-metadata">

**Author:** ![edu.art](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/edu.art/32/25752_2.png) [@edu.art](https://forums.swift.org/u/edu.art)\
**Post date:** [November 8, 2024, 6:15pm UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/3 "2024-11-08T18:15:15Z")

</div>

Combine's swiftinterface doesn't contain anything tricky :)

 ![image](https://global.discourse-cdn.com/swift/original/3X/9/6/9694053084d6f3f2ff937a0bda7fc0959efecea2.jpeg)

---

<div class="post-metadata">

**Author:** ![mbrandonw](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mbrandonw/32/349_2.png) [@mbrandonw](https://forums.swift.org/u/mbrandonw)\
**Post date:** [November 8, 2024, 7:18pm UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/4 "2024-11-08T19:18:55Z")

</div>

> [@mjholgate](#):
>
> If I run this code in Swift 6 (even without the thread sanitiser), I get a runtime exception: "Incorrect actor executor assumption".

Hi @mjholgate, this is discussed in [this part](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/incrementaladoption/#Unmarked-Sendable-Closures) of the Swift 6 migration guide. It is a sharp edge when migrating, but it's just how things are right now. Because `MyClass` is isolated to `@MyActor`, the `sink` trailing closure is automatically inferred to be `@MyActor` too, even though it is not. If you mark the trailing closure as `@Sendable`, then you will get a compiler error forcing you to provide isolation to access `self`.

> [@mjholgate](#):
>
> So this leaves the question about what is special about Combine? Is there a special hack in the compiler to avoid breaking existing pre-concurrency code?

This doesn't have anything to do with Combine, and affects all pre-concurrency code out there.

---

<div class="post-metadata">

**Author:** ![mjholgate](https://avatars.discourse-cdn.com/v4/letter/m/df788c/32.png) [@mjholgate](https://forums.swift.org/u/mjholgate)\
**Post date:** [November 9, 2024, 9:06am UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/5 "2024-11-09T09:06:39Z")

</div>

@mbrandonw just to check my understanding here then, this sharp edge exists because Combine is a Swift 5 module and is being called from a Swift 6 module?

So, I guess if Combine were recompiled by Apple in Swift 6 mode, then it simply wouldn't build in its current form because Swift would reason that it was trying to use a non-Sendable closure across isolation domains?

i.e. to get full static concurrency checking, the entire project and its dependencies needs to be Swift 6 (and not Swift 5/Obj-C, presumably?).

I did a modification to my test code to prove this out using two modules, and it seems to hold true:

**Module (Swift 5)** (a trivial replacement for Combine)

```swift
public class MySubject {
    public var value: Int
    public var closure: ((Int) -> ())?
    
    public init(_ value: Int) {
        self.value = value
    }
    
    public func send(_ value: Int) {
        self.value = value
        DispatchQueue.main.async {
            self.closure?(value)
        }
    }
}

```

**App (Swift 6)**

```swift
@globalActor actor MyActor {
    static var shared: some Actor = MyActor()
}

@MyActor
class MyClass {
    var sub: AnyCancellable?
    let value = MySubject(0)
    var copyValue: Int = 0

    nonisolated init() {
        Task {
            await setup()
        }
    }

    func setup() {
        value.closure = {
            self.copyValue = $0
            print($0)
        }
    }

    func set(value: Int) {
        self.value.send(value)
        for _ in 0..<1000 {
            print(copyValue)
        }
    }

}

struct ContentView: View {
    @State var obj = MyClass()
    var body: some View {
        VStack {
            Button("Go") {
                Task {
                    await obj.set(value: await obj.copyValue + 1)
                    print("Value = \(await obj.copyValue)")
                }
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

```

As expected, this compiles fine, but throws an exception at runtime.  
If I change the languge version of `Module` to Swift 6, also as expected, it won't build (I get a "Sending 'self' risks causing data races") in the body of the `DispatchQueue.main.async`.

Thanks for the very helpful replies and for clearing up my understanding here.

---

<div class="post-metadata">

**Author:** ![mjholgate](https://avatars.discourse-cdn.com/v4/letter/m/df788c/32.png) [@mjholgate](https://forums.swift.org/u/mjholgate)\
**Post date:** [November 9, 2024, 9:37am UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/6 "2024-11-09T09:37:38Z")

</div>

FWIW, I took this a bit further, and tried to make a version of `MySubject` in Swift 6:

```swift
public class MySubject: @unchecked Sendable {
    private var value: Int
    private var _closure: ((Int) -> ())?
    public var closure: ((@Sendable (Int) -> ()))? {
        get {
            fatalError("Not implemented")
        }
        set {
            DispatchQueue.main.async {
                self._closure = newValue
            }
        }
    }
    
    public init(_ value: Int) {
        self.value = value
    }
    
    public func send(_ value: Int) {
        DispatchQueue.main.async {
            self.value = value
            self._closure?(value)
        }
    }
}

```

Pleased to report that with this Swift 6 implementation, I get the expected error in the App:

"Global actor 'MyActor'-isolated property 'copyValue' can not be mutated from a Sendable closure"

i.e. the sharp edge has gone and is detected.

---

<div class="post-metadata">

**Author:** ![mbrandonw](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mbrandonw/32/349_2.png) [@mbrandonw](https://forums.swift.org/u/mbrandonw)\
**Post date:** [November 9, 2024, 1:54pm UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/7 "2024-11-09T13:54:47Z")

</div>

> [@mjholgate](#):
>
> @mbrandonw just to check my understanding here then, this sharp edge exists because Combine is a Swift 5 module and is being called from a Swift 6 module?

Yeah, that is my understanding.

---

<div class="post-metadata">

**Author:** ![mjholgate](https://avatars.discourse-cdn.com/v4/letter/m/df788c/32.png) [@mjholgate](https://forums.swift.org/u/mjholgate)\
**Post date:** [November 10, 2024, 12:21pm UTC](https://forums.swift.org/t/why-no-compiler-error-for-this-swift-concurrency-combine-code/75897/8 "2024-11-10T12:21:15Z")

</div>

Thanks!
