[当使用switch语句时,当.onReceive()
为0时,在timeRemaining
方法中的编译时出现错误。
import SwiftUI
struct TimeMatch: View {
let timer = Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
@State private var timeRemaining: UInt8 = 3
var body: some View {
Text("Time: \(timeRemaining)")
.onReceive(timer) { _ in
switch self.timeRemaining {
case 0...: self.timeRemaining -= 1
case ...0: self.timer.upstream.connect().cancel()
default: fatalError("unimplemented")
}
}
}
}
与if/else
语句相同的代码,没有错误:
Text("Time: \(timeRemaining)")
.onReceive(timer) { _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
} else if self.timeRemaining == 0 {
self.timer.upstream.connect().cancel()
}
怎么了?
您定义了一个无符号int并从0中减去1->崩溃
将其更改为Int并且不会崩溃
@State private var timeRemaining: Int = 3