【发布时间】:2020-05-16 09:51:15
【问题描述】:
我有一个格式为“分钟:秒”的分钟和秒字符串。例如,“5:36”。我想将其转换为 Int 值。例如“5:36”字符串应该是 336 Int 值。如何做到这一点?
【问题讨论】:
-
Int(m) * 60 + Int(s) -
下一次,先尝试自己解决并发布您的尝试。
我有一个格式为“分钟:秒”的分钟和秒字符串。例如,“5:36”。我想将其转换为 Int 值。例如“5:36”字符串应该是 336 Int 值。如何做到这一点?
【问题讨论】:
Int(m) * 60 + Int(s)
let timeString = "5:36"
let timeStringArray = timeString.split(separator: ":")
let minutesInt = Int(timeStringArray[0]) ?? 0
let secondsInt = Int(timeStringArray[1]) ?? 0
let resultInt = minutesInt * 60 + secondsInt
print(resultInt)
【讨论】:
这是一个您可以使用的简单扩展,它也可以验证输入字符串的格式:
import Foundation
extension String {
func toSeconds() -> Int? {
let elements = components(separatedBy: ":")
guard elements.count == 2 else {
print("Provided string doesn't have two sides separated by a ':'")
return nil
}
guard let minutes = Int(elements[0]),
let seconds = Int(elements[1]) else {
print("Either the minute value or the seconds value cannot be converted to an Int")
return nil
}
return (minutes*60) + seconds
}
}
用法:
let testString1 = "5:36"
let testString2 = "35:36"
print(testString1.toSeconds()) // prints: "Optional(336)"
print(testString2.toSeconds()) // prints: "Optional(2136)"
【讨论】:
我在操场上试用了您的示例,代码如下:
import Foundation
let time1String = "0:00"
let time2String = "5:36"
let timeformatter = DateFormatter()
timeformatter.dateFormat = "m:ss"
let time1 = timeformatter.date(from: time1String)
let time2 = timeformatter.date(from: time2String)
if let time1 = time1 {
print(time2?.timeIntervalSince(time1)) // prints: Optional(336.0)
}
【讨论】:
let time2String = "99:36",因为它假定字符串是时钟时间。但不一定是这样。如果它是一个计数秒和分钟的计时器怎么办?如果您只是将字符串拆分并转换为整数,那么从字符串到日期的两次转换也是低效且不必要的。
"5:36" 也不起作用,这是 OP 的原始请求。为此,格式必须为"05:36"。