Skip to content

Misleading error "Sending 'self' risks causing data races" when it's another object that's causing the issue #82021

Open
@nnoniash

Description

@nnoniash

Description

The below code results in the following error on the "print(foo)" line:

Sending 'self' risks causing data races
Task-isolated 'self' is captured by a main actor-isolated closure. main actor-isolated uses in closure may race against later nonisolated uses

despite the issue being that "object" is being captured in the main actors closure, not the fact self is being referenced in this closure. Indeed, when I move the guard line out of the main actor, the code compiles fine.

Reproduction

import UIKit

public class SomeClass : UIView {
    let foo = 16092022
    
    public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            
        Task { @MainActor in
            guard let boo = object as? UIScrollView else {
                return
            }

            print(foo)
        }
    }
}

Expected behavior

The error should be clear about what the issue is which is that object is being captured in a main-actor isolated closure.

Environment

Apple Swift version 6.1 (swift-6.1-RELEASE)
Target: arm64-apple-macosx15.0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.triage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions