Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - Why can't I mutate a variable initially set to a certain parameter when the func was called?

GOAL: I'm trying to make a general struct that can take an array of Ints and go through and set a timer for each one (and show a screen) in succession.

Problem: I get Escaping closure captures mutating 'self' parameter error as shown in the code.

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()
                    }
                }
            })
        }
    }

}

I'm not sure if this has to do with my recursvie function (maybe this is bad form?) and I'm guessing the escaping closure is the func startTimer and the offending the 'self' parameter is the countDownTime parameter, but I'm not really sure what is happening or why it's wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Escaping closure captures mutating 'self' parameter

The escaping closure is the Button's action parameter, and the mutating function is your startTimer function.

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

A simple solution is to change Times to be a class instead of a struct.

Also notice that timeLeft is defined in two places. I don't think this is what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...