Xcode 如何在swift中将数字从字符串保存到变量?
我在xcode中为一个应用程序创建了一个计时器,我正在尝试平均时间,但为了做到这一点,我需要将NSTimer的输出字符串保存到一个变量中。我将其格式化为三个字符串,读作一个字符串,看起来像“00:00:00”,包含分钟、秒和毫秒。如何将各个块保存为变量?我知道如何使用子字符串来隔离各个部分,我只需要将它们保存为变量Xcode 如何在swift中将数字从字符串保存到变量?,xcode,string,swift,variables,var,Xcode,String,Swift,Variables,Var,我在xcode中为一个应用程序创建了一个计时器,我正在尝试平均时间,但为了做到这一点,我需要将NSTimer的输出字符串保存到一个变量中。我将其格式化为三个字符串,读作一个字符串,看起来像“00:00:00”,包含分钟、秒和毫秒。如何将各个块保存为变量?我知道如何使用子字符串来隔离各个部分,我只需要将它们保存为变量 func updateTime() { var currentTime = NSDate.timeIntervalSinceReferenceDate() //Fi
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)"
}
这就是我更新时间的地方,不太确定您还需要看什么。您可以使用类似的方法将计时器字符串转换为
整数数组。
var values = map(split("12:34:56") { $0 == ":" }) { (str) -> Int in return str.toInt() ?? 0 }
注意,您不应该使用NSTimer来计算时间。在计时器启动时设置NSDate,并对当前时间使用timeIntervalSinceDate(从NSDate()获取)
然后,您可以将NSTimerInterval拆分为所需的组件,例如在中,这就是我所做的,我从教程中获得了大部分内容。我根本没有太多使用swift或xcode,这就造成了混乱。那么,你在坚持什么呢?我有输出(00:00:00)。我想将它的一部分(00,有时间)保存为变量,这样我就可以多次进行平均。我只需要将字符串的一部分保存为一个变量。您应该有以秒为单位的时间差的NSTimeInterval。您可以使用上面链接问题中描述的方法从该变量中提取毫秒、秒、分钟、小时等。