Использование локальной переменной updateTimer перед ее объявлением Egg timer - PullRequest
0 голосов
/ 24 апреля 2020

Я только начал изучать программирование, и инструктор попросил нас сделать приложение для таймера яиц. Я попытался запустить ее пример решения, но XCode показывает проблему с кодом на #selector(updateTimer). Ошибка говорит Use of local variable 'updateTimer' before its declaration.

Это код:

class ViewController: UIViewController {
    @IBOutlet weak var progress: UILabel!
    let eggTimes = ["Soft" :3, "Medium":4, "Hard":6]
    var secondsRemaining = 60
    var timer = Timer()

    @IBAction func hardnessSelected(_ sender: UIButton) {
        timer.invalidate()
        let hardness = sender.currentTitle!
        secondsRemaining = eggTimes[hardness]!
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:
                                     #selector(updateTimer), userInfo: nil, repeats: true)
        func updateTimer() {
            if secondsRemaining > 0 {
                print("\(secondsRemaining) seconds left to finish")
                secondsRemaining -= 1
            }
            else {
                timer.invalidate()
                progress.text = "DONE"
            }
        }
    }
}

1 Ответ

0 голосов
/ 24 апреля 2020

Проблема, с которой вы сталкиваетесь, заключается в том, что func updateTimer объявлен под #selector и, следовательно, еще не «доступен», если говорить проще. Вероятно, вы хотели бы переместить функцию за пределы hardnessSelected следующим образом:

class ViewController: UIViewController {
    @IBOutlet weak var progress: UILabel!

    let eggTimes = ["Soft" :3, "Medium":4, "Hard":6]
    var secondsRemaining = 60
    var timer = Timer()

    @IBAction func hardnessSelected(_ sender: UIButton) {
        self.timer.invalidate()
        let hardness = sender.currentTitle!
        self.secondsRemaining = self.eggTimes[hardness]!
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
    }

    @objc func updateTimer() {
        if self.secondsRemaining > 0 {
            print("\(self.secondsRemaining) seconds left to finish")
            self.secondsRemaining -= 1
        }
        else {
            self.timer.invalidate()
            self.progress.text = "DONE"
        }
    }
}

Вам также необходимо добавить @objc перед именем функции, чтобы открыть ее для Obj C среды выполнения. Вы можете прочитать больше об этом здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...