ActorIsolated
A generic wrapper for isolating a mutable value to an actor.
This declaration is deprecated: Use 'LockIsolated' instead.
final actor ActorIsolated<Value>
This type is most useful when writing tests for when you want to inspect what happens inside an async operation.
For example, suppose you have a feature such that when a button is tapped you track some analytics:
struct AnalyticsClient {
var track: (String) async -> Void
}
class FeatureModel: ObservableObject {
let analytics: AnalyticsClient
// ...
func buttonTapped() {
// ...
await self.analytics.track("Button tapped")
}
}
Then, in tests we can construct an analytics client that appends events to a mutable array rather than actually sending events to an analytics server. However, in order to do this in a safe way we should use an actor, and ActorIsolated
makes this easy:
func testAnalytics() async {
let events = ActorIsolated<[String]>([])
let analytics = AnalyticsClient(
track: { event in await events.withValue { $0.append(event) } }
)
let model = FeatureModel(analytics: analytics)
model.buttonTapped()
await events.withValue {
XCTAssertEqual($0, ["Button tapped"])
}
}
To synchronously isolate a value, see LockIsolated
.