我的打印功能在我的代码中多次运行,这是下面的代码和运行结果:
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)")
}
}
}
}