Xcode playground issues - Mutating a global variable

Hello,

I have a very simple code example that I tried to run in Xcode playground:

var num1: Int = 5

func foo (number: Int) -> Void {

num1 += 1

}

and I get the following error: "Main actor-isolated var 'num1' can not be mutated from a nonisolated context"

When I tried this code in a project on Xcode however, it' s completely fine and doesn't give any errors.

I'm very new to Xcode and swift in general, so I would appreciate any help as I cannot figure out if this is an issue from Xcode or something inherent in the language that I don't understand.

I suspect the difference is that your playground is set to Swift 6 language mode, whereas your Xcode project is set to Swift 5 language mode.

In Swift 6 mode, the compiler identifies this as a potential data race because top-level global variables are implicitly @MainActor, i.e. they can only be accessed from other @MainActor contexts. The easiest fix is to add @MainActor to the function:

@MainActor func foo(…

In a playground, you can set the language mode in the File Inspector (right sidebar, first tab) under "Swift Version". In an Xcode project, set Swift language mode is set under Build Settings for your target and/or project.

1 Like

I just checked the swift versions and your'e absolutely right! Thanks

1 Like