目标:我正在尝试创建一个通用结构,它可以接受一组 Int 并连续为每个 Int 数组设置一个计时器(并显示一个屏幕)。
问题:我收到 Escapeingclosure captures mutating 'self'parameter
错误,如代码所示。
import SwiftUI
struct ContentView: View {
@State private var timeLeft = 10
@State private var timers = Timers(timersIWant: [6, 8, 14])
// var timersIWantToShow: [Int] = [6, 8, 14]
var body: some View {
Button(action: {self.timers.startTimer(with: self.timeLeft)}) {
VStack {
Text("Hello, World! \(timeLeft)")
.foregroundColor(.white)
.background(Color.blue)
.font(.largeTitle)
}
}
}
struct Timers {
var countDownTimeStart: Int = 0
var currentTimer = 0
var timersIWant: [Int]
mutating func startTimer(with countDownTime: Int) {
var timeLeft = countDownTime
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in //Escaping closure captures mutating 'self' parameter
if timeLeft > 0 {
timeLeft -= 1
} else {
timer.invalidate()
self.currentTimer += 1
if self.currentTimer < self.timersIWant.count {
self.startTimer(with: self.timersIWant[self.currentTimer])
} else {
timer.invalidate()
}
}
})
}
}
}
我不确定这是否与我的 recursvie 函数有关(也许这是不好的形式?),我猜测转义闭包
是func startTimer
并且令人讨厌的 'self' 参数
是 countDownTime
参数,但我不太确定发生了什么或为什么它是错误的。
最佳答案
Escaping closure captures mutating 'self' parameter
转义闭包是 Button
的 action
参数,而变异函数是您的 startTimer
函数。
Button(action: {self.timers.startTimer(with: self.timeLeft)}) {
一个简单的解决方案是将 Times
更改为 class
而不是 struct
。
另请注意,timeLeft
是在两个位置定义的。我认为这不是您想要的。
关于swift - 为什么我不能在调用 func 时改变最初设置为某个参数的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684743/