switch语句不适用于SwiftUI中的方法.onReceive()

问题描述 投票:0回答:1

[当使用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()
                }

怎么了?

switch-statement swiftui combine
1个回答
0
投票

您定义了一个无符号int并从0中减去1->崩溃

将其更改为Int并且不会崩溃

@State private var timeRemaining: Int = 3
© www.soinside.com 2019 - 2024. All rights reserved.