Skip to content

Commit b7363fc

Browse files
committed
[a-swift-tour] Concurrencyを追加
1 parent 2b4d9ee commit b7363fc

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

welcome-to-swift/a-swift-tour.md

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Swiftツアー\(A Swift Tour\)
22

3-
最終更新日: 2023/5/27
3+
最終更新日: 2023/8/27
44
原文: https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html
55

66
Swift の特徴とシンタックスを探る。
@@ -679,6 +679,69 @@ Task {
679679
// Hello Guest, user ID 97
680680
```
681681

682+
平行コードを構造化するために、タスクグループ\(_task group_\)を使います。
683+
684+
```swift
685+
let userIDs = await withTaskGroup(of: Int.self) { taskGroup in
686+
for server in ["primary", "secondary", "development"] {
687+
taskGroup.addTask {
688+
return await fetchUserID(from: server)
689+
}
690+
}
691+
692+
var results: [Int] = []
693+
for await result in taskGroup {
694+
results.append(result)
695+
}
696+
return results
697+
}
698+
```
699+
700+
アクターはクラスと似ていますが、異なる非同期関数が同時に同じアクターのインスタンスに安全にアクセスできる点が異なります。
701+
702+
```swift
703+
actor ServerConnection {
704+
var server: String = "primary"
705+
private var activeUsers: [Int] = []
706+
func connect() async -> Int {
707+
let userID = await fetchUserID(from: server)
708+
// ... communicate with server ...
709+
activeUsers.append(userID)
710+
return userID
711+
}
712+
}
713+
```
714+
715+
<!--
716+
- test: `guided-tour`
717+
```swifttest
718+
-> actor Oven {
719+
var contents: [String] = []
720+
func bake(_ food: String) -> String {
721+
contents.append(food)
722+
// ... wait for food to bake ...
723+
return contents.removeLast()
724+
}
725+
}
726+
```
727+
-->
728+
729+
アクターのメソッドを呼び出す、もしくはそのプロパティの 1 つにアクセスする時に、
730+
そのアクター上で実行している他のコードが完了するのを待つことを示すために `await` をつける必要があります。
731+
732+
```swift
733+
let server = ServerConnection()
734+
let userID = await server.connect()
735+
```
736+
737+
<!--
738+
- test: `guided-tour`
739+
```swifttest
740+
-> let oven = Oven()
741+
-> let biscuits = await oven.bake("biscuits")
742+
```
743+
-->
744+
682745
## プロトコルと拡張\(Protocols and Extensions\)
683746

684747
プロトコルを宣言するために `protocol` を使います。

0 commit comments

Comments
 (0)