IOS 将字符串转换为整数

IOS Convert String to Int

我需要将字符串转换为 Int,这样我就可以使用 if > 语句来启用和禁用按钮。正如您从 updateStopwatch 中的注释行中看到的那样,我尝试了多种转换方法但没有成功

我的 Class 看起来像

class Stopwatch {

    var startTime:Date?

    func startTimer() {
        startTime = Date();
    }

    func elapsedTimeSinceStart() -> String {
        var elapsed = 0.0;
        if let elapsedTime = startTime {
            if firstHalfTime {
                elapsed = elapsedTime.timeIntervalSinceNow
            } else {
               elapsed = elapsedTime.timeIntervalSinceNow - 45*60
            }
        }
        elapsed = -elapsed
        let minutes = Int(floor((elapsed / 60)));
        let seconds = Int(floor((elapsed.truncatingRemainder(dividingBy: 60))));
//        print(elapsed)
        let timeString = String(format: "%02d:%02d", minutes, seconds)
//        print(timeString)
        return timeString
    }
}

我的定时更新功能

func updateStopwatch() {

        let stopWatchString = stopWatch.elapsedTimeSinceStart()
        stopwatchLabel.text = stopWatchString

//        let minutesString:Int = Int(stopWatchString)!
//        minutes = minutesString

          if minutes > 1 {
            endFirstHalf.isEnabled = true
            self.endFirstHalf.alpha = 1
        }
    } 

插入冒号 (:) 后无法将字符串转换回 Int

我向 return 推荐 TimeInterval

func elapsedTimeSinceStart() -> TimeInterval {
    var elapsed = 0.0
    if let elapsedTime = startTime {
        if firstHalfTime {
            elapsed = elapsedTime.timeIntervalSinceNow
        } else {
            elapsed = elapsedTime.timeIntervalSinceNow - 45*60
        }
    }
    elapsed = -elapsed
    return elapsed
}

并在 updateStopwatch()

中进行计算
func updateStopwatch() {

    let elapsed = stopWatch.elapsedTimeSinceStart()
    let minutes = Int(floor(elapsed / 60)));
    let seconds = Int(floor((elapsed.truncatingRemainder(dividingBy: 60))));
    let stopWatchString = String(format: "%02d:%02d", minutes, seconds)

    stopwatchLabel.text = stopWatchString

    if minutes > 1 {
        endFirstHalf.isEnabled = true
        self.endFirstHalf.alpha = 1
    }
} 

此代码的作用相同,但使用的更现代一些 API

let dateComponentsFormatter : DateComponentsFormatter = {
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.minute, .second]
    return formatter
}()

func elapsedTimeSinceStart() -> DateComponents {
    var components = DateComponents(minute: 0, second:0)
    if let elapsedTime = startTime {
        components = Calendar.current.dateComponents([.minute, .second], from: elapsedTime, to: Date())
        if !firstHalfTime { components.minute! += 45 }
    }
    return components
}

func updateStopwatch() {

    let components = elapsedTimeSinceStart()
    stopwatchLabel.text = dateComponentsFormatter.string(from: components)

    if components.minute! > 1 {
      endFirstHalf.isEnabled = true
      self.endFirstHalf.alpha = 1
    }
}