为什么这个print()每次触发两次?

时间:2020-01-19 17:46:26

标签: ios swift swiftui

我的打印功能在我的代码中多次运行,这是下面的代码和运行结果:

struct ContentView: View {
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State private var counter = 0

var body: some View {
   Text("Hello, World!")
       .onReceive(timer) { time in
            if self.counter == 5 {
            self.timer.upstream.connect().cancel()
            }
            else {
                self.counter += 1
                print("The time is now \(time)")
            }
       }
   }
}

running result

0 个答案:

没有答案