使用未解析的标识符'timeR'->调用嵌套函数

问题描述 投票:0回答:1
import UIKit

class ViewController: UIViewController {

    var timer:Timer?
    @objc func onTimerFires() {
        var timeLeft:Int = timeR()

        timeLeft -= 1
        print("\(timeLeft) seconds left")

        if timeLeft <= 0 {
            timer!.invalidate()
            timer = nil
        }
    }

    @IBAction func hardnessSelected(_ sender: UIButton) {

        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)

        let eggTimes:[String:Int] = [
            "Soft":5,
            "Medium":7,
            "Hard":12,
        ]

        let hardness = sender.currentTitle!

        func timeR() -> Int {
            if eggTimes[hardness]! == 5{
                return(120)
            }
            else if eggTimes[hardness]! == 7{
                return(420)
            }
            else {
                return(720)
            }
        }
        print(eggTimes[hardness]!)
    }
}

我无法拉出嵌套函数,有没有一种方法可以进行内部函数调用。谢谢。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9oTkJmVi5wbmcifQ==” alt =“在此处输入图像描述”>

swift function-call nested-function
1个回答
1
投票

timeR函数在hardnessSelected内部定义为局部函数,因此仅在其包含函数hardnessSelected内部可见。

如果要将hardness的值传递给onTimerFires,则需要将其保存到ViewController的实例属性中,onTimerFireshardnessSelected都可以访问。然后将timeR移到onTimerFires并传入hardness的值。

class ViewController: UIViewController {

    private let eggTimes:[String:Int] = [
        "Soft":5,
        "Medium":7,
        "Hard":12,
    ]

    var hardness: String?

    var timer:Timer?

    @objc func onTimerFires() {
        func timeR(hardness: String) -> Int {
            if eggTimes[hardness] == 5 {
                return 120
            } else if eggTimes[hardness] == 7{
                return 420
            } else {
                return 720
            }
        }

        var timeLeft:Int = timeR(hardness: hardness ?? "")

        timeLeft -= 1
        print("\(timeLeft) seconds left")

        if timeLeft <= 0 {
            timer!.invalidate()
            timer = nil
        }
    }

    @IBAction func hardnessSelected(_ sender: UIButton) {

        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)

        hardness = sender.currentTitle

        print(time)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.