【问题标题】:How to save the number from a string to a variable in swift?如何快速将字符串中的数字保存到变量中?
【发布时间】:2015-07-07 15:28:48
【问题描述】:

我在 xcode 中为应用程序制作了一个计时器,我正在尝试平均时间,但为了做到这一点,我需要将 NSTimer 的输出字符串保存到一个变量中。我将它格式化为三个字符串,读为一个,看起来像“00:00:00”,带有分钟、秒和毫秒。如何将单个块保存为变量?我知道如何使用子字符串来隔离片段,我只需要将它们保存为变量。

func updateTime() {
    var currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.
    var elapsedTime: NSTimeInterval = currentTime - startTime

    //calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.
    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
    let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel
    timerLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}

那里是我更新时间的地方,不知道你还需要看什么。

【问题讨论】:

    标签: xcode string swift variables var


    【解决方案1】:

    注意,您不应该使用 NSTimer 来计算时间。在计时器启动时设置一个 NSDate,并使用 timeIntervalSinceDate 对当前时间(从 NSDate() 获取)

    NSTimer is not accurate enough for timing

    然后你可以把 NSTimerInterval 拆分成你想要的组件,比如this question

    【讨论】:

    • 这就是我所做的,我从教程中获得了大部分内容。我根本没有使用过 swift 或 xcode,因此很混乱。
    • 那你还在坚持什么?
    • 我有输出 (00:00:00)。我想将其中的一部分(00,会有时间)保存为变量,这样我就可以多次进行平均。我只需要将部分字符串保存为变量。
    • 你应该有 NSTimeInterval 的时间差(以秒为单位)。您可以使用上面链接问题中描述的方法从该变量中提取毫秒、秒、分钟、小时等。
    【解决方案2】:

    您可以使用类似的方法将计时器字符串转换为 Ints 数组

    var values = map(split("12:34:56") { $0 == ":" }) { (str) -> Int in return str.toInt() ?? 0 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2019-01-05
      相关资源
      最近更新 更多