swift - 为什么我不能在调用 func 时改变最初设置为某个参数的变量?

标签 swift struct swiftui

目标:我正在尝试创建一个通用结构,它可以接受一组 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

转义闭包是 Buttonaction 参数,而变异函数是您的 startTimer 函数。

        Button(action: {self.timers.startTimer(with: self.timeLeft)}) {

一个简单的解决方案是将 Times 更改为 class 而不是 struct

另请注意,timeLeft 是在两个位置定义的。我认为这不是您想要的。

关于swift - 为什么我不能在调用 func 时改变最初设置为某个参数的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684743/

相关文章:

iOS - Swift - 使用数组和条件循环

swift - 安装 pod 时遇到问题

c - 无效的初始化程序编译器错误在结构数组的malloc

c++ - 在 C++ 中将结构类型转换为整数,反之亦然

Swiftlint 覆盖与 SPM 相关的项目设置

ios - .noDataText 未在图表内更新。 swift 2

matlab - 如何找到结构体数组中的最大值

swift - 如何在XCTestCase的viewModel中正确测试通过发布者更改的var

swiftui - 在 SwiftUI 中创建胶囊风格进度

swift - Swift 包中的 UI 测试