iosswiftxcodeswift-playground

Main Actor Isolation Error in Xcode Playground for Simple Swift Code


I’m new to Swift and running into an issue with actor isolation in Xcode Playgrounds. When I try to run the following simple code, I get the error message about actor isolation, and I’m not sure why.

error: Testone.xcplaygroundpage:7:35: main actor-isolated var 'connectionSuccess' can not be referenced from a nonisolated context
    if let newConnectionSuccess = connectionSuccess {
                                  ^

Testone.xcplaygroundpage:4:5: note: var declared here
var connectionSuccess: Bool? = nil
    ^

Testone.xcplaygroundpage:6:6: note: add '@MainActor' to make global function 'checkConnection()' part of global actor 'MainActor'
func checkConnection() -> Bool {
     ^
@MainActor

Code Swift v6.0 and Xcode v16

import Foundation

var connectionSuccess: Bool? = nil

func checkConnection() -> Bool {
    if let newConnectionSuccess = connectionSuccess {
        return newConnectionSuccess
    }
    
    return false
}

checkConnection()

I'm not working with threads or doing anything complicated, just trying to check the value of an optional Bool. The error suggests adding @MainActor, but I’ve seen similar code in a tutorial without this requirement. Is this something new in Swift? Appreciate your help with this.


Solution

  • Is this something new in Swift?

    Kind of? Complete concurrency checking is now mandatory in Swift 6, whereas previously you need to opt-in with the -strict-concurrency=complete option.

    The problem here is that connectionSuccess is implicitly isolated to the main actor because it is variable declared at the top level that allows statements (like in a playground/Swift script/main.swift etc).

    checkConnection is not isolated to the main actor (it's not isolated to any actor), so it cannot synchronously access connectionSuccess.

    So you should just add @MainActor to checkConnection as the error suggests.


    You can lower the Swift version of a playground by going into the .playground folder, and find the contents.xcplayground file. It looks like this

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <playground version='7.0' target-platform='macos' swift-version='6' buildActiveScheme='true' importAppTypes='true'/>
    

    Just change the swift-version='6' part to your desired Swift version.