将字典值实现为倒计时计时器

Implement a dictionary value into a count down timer

我正在做一个应用程序测验,其中我想将字典的值实现为倒数计时器的初始值,所以如果“软”键是目标,倒数计时器从 300 开始而不是60

import UIKit

class ViewController: UIViewController {
    let eggTimes :[String:Int]=["Soft":300,"Medium":420,"Hard":720
    ]
  var count: Int = 60
    
    func startCountDown() {
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter() {
        if count>0 {
            count-=1
            countDownLabel.text = "\(count)"
            print(count)
        }
    }
    
    @IBOutlet weak var countDownLabel: UILabel!
    @IBAction func hardnessSelected(_ sender: UIButton) {
        startCountDown()
        let hardness=sender.currentTitle!
        let result = eggTimes[hardness]!
        print(result)
        
      
       
       
   
    }
   
    
     
    
} ```
    let hardness=sender.currentTitle!
    count = eggTimes[hardness]!
    startCountDown()

在开始倒计时前设置count

@IBAction func hardnessSelected(_ sender: UIButton) {
    let hardness = sender.currentTitle!
    count = eggTimes[hardness]!
    startCountDown()
}

但是给 3 个按钮分配标签更容易,三个值 300、420 ​​和 720。

那你可以把字典删了写

@IBAction func hardnessSelected(_ sender: UIButton) {
    count = sender.tag
    startCountDown()
}