回答編集履歴
1
追記
test
CHANGED
@@ -79,3 +79,63 @@
|
|
79
79
|
}
|
80
80
|
|
81
81
|
```
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
---
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
Thread を使う方法も書いておきます。
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
```swift
|
94
|
+
|
95
|
+
@IBAction func countWords() {
|
96
|
+
|
97
|
+
let str = """
|
98
|
+
|
99
|
+
Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do. Once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?"
|
100
|
+
|
101
|
+
"""
|
102
|
+
|
103
|
+
let arr: [String] = str.components(separatedBy: " ")
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
Thread.detachNewThread {
|
108
|
+
|
109
|
+
// バックグラウンドスレッドで処理を行う。
|
110
|
+
|
111
|
+
for i in 0..<arr.count {
|
112
|
+
|
113
|
+
let word = arr[i]
|
114
|
+
|
115
|
+
let count = arr.filter { $0 == word }.count
|
116
|
+
|
117
|
+
print(i)
|
118
|
+
|
119
|
+
print("(word)が(count)個ありました")
|
120
|
+
|
121
|
+
|
122
|
+
|
123
|
+
// UI の更新はメインスレッドで行う必要がある。
|
124
|
+
|
125
|
+
DispatchQueue.main.async {
|
126
|
+
|
127
|
+
self.totalCountLabel.text = "計(i)個"
|
128
|
+
|
129
|
+
}
|
130
|
+
|
131
|
+
|
132
|
+
|
133
|
+
Thread.sleep(forTimeInterval: 0.1)
|
134
|
+
|
135
|
+
}
|
136
|
+
|
137
|
+
}
|
138
|
+
|
139
|
+
}
|
140
|
+
|
141
|
+
```
|