Skip to content

Swift 6 erroneously thinks struct initializer and read-only computed property are main-actor isolated #82812

Open
@softwarenerd

Description

@softwarenerd

Description

Swift 6 is driving me crazy by erroneously inferring main actor-isolation on things it shouldn't.

See: https://github.com/softwarenerd/AwfulMainActorIsolatedExample

Reproduction

Just throw this code into JsonWebToken.swift in a new macOS SwiftUI app. There's no need to reference it anywhere in the SwiftUI.

import Foundation

struct Claims: Codable {
    let sub: UUID
}

struct JsonWebToken: Codable {
    let claims: Claims
    let accountIdentifier1: UUID
    
    // ❗Swift 6 erroneously thinks this is main actor-isolated!!!
    init(claims: Claims) {
        self.claims = claims
        self.accountIdentifier1 = claims.sub
    }

    // ❗Swift 6 erroneously thinks this is main actor-isolated!!!
    var accountIdentifier2: UUID {
        return claims.sub
    }
}

struct Session {
    let jsonWebToken: JsonWebToken
}

actor BackgroundWorker {
    func test1() {
        // ❌ This results in an error in Swift 6:
        // Call to main actor-isolated initializer 'init(claims:)' in a synchronous actor-isolated context; this is an error in the Swift 6 language mode.
        let jsonWebToken = JsonWebToken(claims: Claims(sub: UUID()))
        
        // This is OK.
        print("Account ID:: \(jsonWebToken.accountIdentifier1)")

        // ❌ This results in an error in Swift 6:
        // Main actor-isolated property 'accountIdentifier' can not be referenced on a nonisolated actor instance; this is an error in the Swift 6 language mode.
        print("Account ID:: \(jsonWebToken.accountIdentifier2)")
    }
    
    func test2(session: Session) {
        // This is OK.
        let accountIdentifier1 = session.jsonWebToken.accountIdentifier1
                
        // ❌ This results in an error in Swift 6:
        // Main actor-isolated property 'accountIdentifier' can not be referenced on a nonisolated actor instance; this is an error in the Swift 6 language mode.
        let accountIdentifier2 = session.jsonWebToken.accountIdentifier2
        
        print("Account ID: \(accountIdentifier1)")
        print("Account ID: \(accountIdentifier2)")
    }
}

Expected behavior

I should be able to instantiate JsonWebToken and access accountIdentifier2 without getting main actor-isolation errors.

Environment

swift-driver version: 1.120.5 Apple Swift version 6.1.2 (swiftlang-6.1.2.1.2 clang-1700.0.13.5)
Target: arm64-apple-macosx16.0

Additional information

Image

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