Skip to content

Commit 40dee84

Browse files
authored
Show concurrency in the guided tour (#154)
Fixes: rdar://78794648
2 parents 82623c9 + b2bbaac commit 40dee84

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

TSPL.docc/GuidedTour/GuidedTour.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1842,6 +1842,76 @@ Task {
18421842
```
18431843
-->
18441844

1845+
Use task groups to structure concurrent code.
1846+
1847+
```swift
1848+
let userIDs = await withTaskGroup(of: Int.self) { taskGroup in
1849+
for server in ["primary", "secondary", "development"] {
1850+
taskGroup.addTask {
1851+
return await fetchUserID(from: server)
1852+
}
1853+
}
1854+
1855+
var results: [Int] = []
1856+
for await result in taskGroup {
1857+
results.append(result)
1858+
}
1859+
return results
1860+
}
1861+
```
1862+
1863+
Actors are similar to classes,
1864+
except they ensure that different asynchronous functions
1865+
can safely interact with an instance of the same actor at the same time.
1866+
1867+
```swift
1868+
actor ServerConnection {
1869+
var server: String = "primary"
1870+
private var activeUsers: [Int] = []
1871+
func connect() async -> Int {
1872+
let userID = await fetchUserID(from: server)
1873+
// ... communicate with server ...
1874+
activeUsers.append(userID)
1875+
return userID
1876+
}
1877+
}
1878+
```
1879+
1880+
<!--
1881+
- test: `guided-tour`
1882+
1883+
```swifttest
1884+
-> actor Oven {
1885+
var contents: [String] = []
1886+
func bake(_ food: String) -> String {
1887+
contents.append(food)
1888+
// ... wait for food to bake ...
1889+
return contents.removeLast()
1890+
}
1891+
}
1892+
```
1893+
-->
1894+
1895+
When you call a method on an actor or access one of its properties,
1896+
you mark that code with `await`
1897+
to indicate that it might have to wait for other code
1898+
that's already running on the actor to finish.
1899+
1900+
```swift
1901+
let server = ServerConnection()
1902+
let userID = await server.connect()
1903+
```
1904+
1905+
<!--
1906+
- test: `guided-tour`
1907+
1908+
```swifttest
1909+
-> let oven = Oven()
1910+
-> let biscuits = await oven.bake("biscuits")
1911+
```
1912+
-->
1913+
1914+
18451915
## Protocols and Extensions
18461916

18471917
Use `protocol` to declare a protocol.

0 commit comments

Comments
 (0)