将Date String转换为Int Swift

时间:2015-10-18 19:49:34

标签: ios swift swift2

我正在尝试转换字符串:

let time = "7:30"

到整数:

let hour : Int = 7
let minutes : Int = 30

我目前正在循环播放字符串:

for char in time.characters {
}

但我无法弄清楚如何将char转换为int。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:5)

使用String.componentsSeparatedByStringtime字符串拆分为部分:

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,可以将时间字符串拆分为以下部分:

let timeParts = time.characters.split(":").map(String.init)

答案 1 :(得分:4)

@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]

答案 2 :(得分:1)

您可以按:字符拆分字符串,然后将结果转换为Int:

let timeStringArray = time.componentsSeparatedByString(":")
if timeStringArray.count == 2 {
   hour = timeStringArray[0].toInt
   minutes = timeStringArray[1].toInt()
}