【问题标题】:Use of unresolved identifier 'timeR' -> Calling a nested function使用未解析的标识符“timeR”-> 调用嵌套函数
【发布时间】:2020-04-06 15:16:17
【问题描述】:
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]!)
    }
}

我无法拉出嵌套函数,有没有办法进行内部函数调用。谢谢。

【问题讨论】:

    标签: swift function-call nested-function


    【解决方案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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      相关资源
      最近更新 更多