Skip to content

Commit d75ad5b

Browse files
Make actor example more useful (#107)
* fix #105; make a useful actor type * Actor example code
1 parent 78b900b commit d75ad5b

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Guide.docc/CommonProblems.md

+15
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,21 @@ But further, data that is passed into or out of the actor may itself
620620
need to cross the isolation boundary.
621621
This can result in the need for yet more `Sendable` types.
622622

623+
```swift
624+
actor Style {
625+
private var background: ColorComponents
626+
627+
func applyBackground(_ color: ColorComponents) {
628+
// make use of non-Sendable data here
629+
}
630+
}
631+
```
632+
633+
By moving both the non-Sendable data *and* operations on that data into the
634+
actor, no isolation boundaries need to be crossed.
635+
This provides a `Sendable` interface to those operations that can be freely
636+
accessed from any asynchronous context.
637+
623638
#### Manual Synchronization
624639

625640
If you have a type that is already doing manual synchronization, you can

Sources/Examples/Boundaries.swift

+23-1
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,24 @@ func globalActorIsolated_updateStyle(backgroundColor: GlobalActorIsolatedColorCo
8181
applyBackground(backgroundColor)
8282
}
8383

84+
// MARK: actor isolation
85+
86+
/// An actor that assumes the responsibility of managing the non-Sendable data.
87+
actor Style {
88+
private var background: ColorComponents
89+
90+
init(background: ColorComponents) {
91+
self.background = background
92+
}
93+
94+
func applyBackground() {
95+
// make use of background here
96+
}
97+
}
98+
8499
func exerciseBoundaryCrossingExamples() async {
85100
print("Isolation Boundary Crossing Examples")
86-
101+
87102
#if swift(<6.0)
88103
print(" - updateStyle(backgroundColor:) passing its argument unsafely")
89104
#endif
@@ -115,4 +130,11 @@ func exerciseBoundaryCrossingExamples() async {
115130
let components = await GlobalActorIsolatedColorComponents()
116131

117132
await globalActorIsolated_updateStyle(backgroundColor: components)
133+
134+
print(" - using an actor")
135+
let actorComponents = ColorComponents()
136+
137+
let actor = Style(background: actorComponents)
138+
139+
await actor.applyBackground()
118140
}

0 commit comments

Comments
 (0)