将datestring转换为Int Swift
我想转换string:
let time = "7:30"
整数:
let hour : Int = 7 let minutes : Int = 30
我目前正在循环的string:
for char in time.characters { }
但我不知道如何将一个字符转换为一个int。 任何帮助将不胜感激。
@alex_p和@mixel的答案是正确的,但也可以用Swift split
函数来完成:
let time = "7:30" let components = time.characters.split { $0 == ":" } .map { (x) -> Int in return Int(String(x))! } let hours = components[0] let minutes = components[1]
使用String.componentsSeparatedByString
将time
string拆分为部分:
import Foundation let time = "7:30" let timeParts = time.componentsSeparatedByString(":") if timeParts.count == 2 { if let hour = Int(timeParts[0]), let minute = Int(timeParts[1]) { // use hour and minute } }
如果您不想import Foundation
,则可以将时间string拆分为以下部分:
let timeParts = time.characters.split(":").map(String.init)
你可以通过字符分割string,然后将结果转换为Int:
let timeStringArray = time.componentsSeparatedByString(":") if timeStringArray.count == 2 { hour = timeStringArray[0].toInt minutes = timeStringArray[1].toInt() }