Reputation: 9430
I try to check the actor's behavior. This is a new feature provided by Swift5.5.
I've created a playground with an example code from the official documentation swift.org:
import Foundation
actor TemperatureLogger {
let label: String
var measurements: [Int]
private(set) var max: Int
init(label: String, measurement: Int) {
self.label = label
self.measurements = [measurement]
self.max = measurement
}
}
let logger = TemperatureLogger(label: "Outdoors", measurement: 25)
print(await logger.max)
// Prints "25"
But my compiler fails on this example:
Swift Compiler Error:
'await' in a function that does not support concurrency
Actor-isolated property 'max' can only be referenced from inside the actor
So how to access an actor-isolated property?
Maybe it's a bug in the compiler or in the example code?
Xcode Version 13.0 beta (13A5154h) Swift Version 5.5
Upvotes: 25
Views: 33257
Reputation: 7708
Put the access in an Task
block.
Actor isolated properties synchronise and enforce exclusive access through the "cooperative thread pool" and could suspend, so this needs to run asynchronously.
let logger = TemperatureLogger(label: "Outdoors", measurement: 25)
Task {
print(await logger.max)
// Prints "25"
}
Upvotes: 25