質問編集履歴
1
いただいた追記依頼から更新しています
title
CHANGED
File without changes
|
body
CHANGED
@@ -138,4 +138,98 @@
|
|
138
138
|
何かが足りないのだと思うのですが、解決できません。
|
139
139
|
ものすごく基礎的なことをお聞きしていると思うのですが、お教えいただければ幸いです。
|
140
140
|
|
141
|
-
よろしくお願いします。
|
141
|
+
よろしくお願いします。
|
142
|
+
|
143
|
+
---------------------------
|
144
|
+
その後、hoshiさんの③のコメントにあるようにstructに使えないということで、質問の上にあったStopwatch.swiftを
|
145
|
+
```
|
146
|
+
import SwiftUI
|
147
|
+
|
148
|
+
class Stopwatch2: ObservableObject {
|
149
|
+
|
150
|
+
/// String to show in UI
|
151
|
+
@Published private(set) var message = "Not running"
|
152
|
+
|
153
|
+
/// Is the timer running?
|
154
|
+
@Published private(set) var isRunning = false
|
155
|
+
|
156
|
+
/// Time that we're counting from
|
157
|
+
private var startTime: Date? { didSet { saveStartTime() } }//<--④
|
158
|
+
|
159
|
+
/// The timer
|
160
|
+
private var timer: AnyCancellable?// <--⑤
|
161
|
+
|
162
|
+
init() {
|
163
|
+
startTime = fetchStartTime() //<--⑥
|
164
|
+
|
165
|
+
if startTime != nil {
|
166
|
+
start() //<--⑦
|
167
|
+
}
|
168
|
+
}
|
169
|
+
}
|
170
|
+
|
171
|
+
// MARK: - Public Interface
|
172
|
+
|
173
|
+
extension Stopwatch {
|
174
|
+
func start() {
|
175
|
+
timer?.cancel() // cancel timer if any. <--⑧
|
176
|
+
|
177
|
+
if startTime == nil { //<--⑨ 以下同様のエラー多数
|
178
|
+
startTime = Date()
|
179
|
+
}
|
180
|
+
|
181
|
+
message = ""
|
182
|
+
|
183
|
+
timer = Timer
|
184
|
+
.publish(every: 0.1, on: .main, in: .common)
|
185
|
+
.autoconnect()
|
186
|
+
.sink { [weak self] _ in
|
187
|
+
guard
|
188
|
+
let self = self,
|
189
|
+
let startTime = self.startTime
|
190
|
+
else { return }
|
191
|
+
|
192
|
+
let now = Date()
|
193
|
+
let elapsed = now.timeIntervalSince(startTime)
|
194
|
+
|
195
|
+
guard elapsed < 60 else {
|
196
|
+
self.stop()
|
197
|
+
return
|
198
|
+
}
|
199
|
+
|
200
|
+
self.message = String(format: "%0.1f", elapsed)
|
201
|
+
}
|
202
|
+
|
203
|
+
isRunning = true
|
204
|
+
}
|
205
|
+
|
206
|
+
func stop() {
|
207
|
+
timer?.cancel()
|
208
|
+
timer = nil
|
209
|
+
startTime = nil
|
210
|
+
isRunning = false
|
211
|
+
message = "Not running"
|
212
|
+
}
|
213
|
+
}
|
214
|
+
|
215
|
+
// MARK: - Private implementation
|
216
|
+
|
217
|
+
private extension Stopwatch {
|
218
|
+
func saveStartTime() {
|
219
|
+
if let startTime = startTime {
|
220
|
+
UserDefaults.standard.set(startTime, forKey: "startTime")
|
221
|
+
} else {
|
222
|
+
UserDefaults.standard.removeObject(forKey: "startTime")
|
223
|
+
}
|
224
|
+
}
|
225
|
+
|
226
|
+
func fetchStartTime() -> Date? {
|
227
|
+
UserDefaults.standard.object(forKey: "startTime") as? Date
|
228
|
+
}
|
229
|
+
}
|
230
|
+
```
|
231
|
+
のようにし、③のエラーは消えたのですが、その代わりclass Stopwatch下の各変数がCannot find '????' in scopeになってしまいます。
|
232
|
+
例えば④であれば、Cannot find 'saveStartTime' in scopeclass ⑤であればCannot find 'AnyCancellable' in scopeclass です。
|
233
|
+
class Stopwatch2: ObservableObject {以下を同一スコープの中に入れる方法がわかりません。
|
234
|
+
|
235
|
+
質問の仕方が稚拙とは思いますがよろしくお願いします。
|