【问题标题】:Convert Date String to Int Swift将日期字符串转换为 Int Swift
【发布时间】:2015-10-18 19:49:34
【问题描述】:

我正在尝试转换字符串:

let time = "7:30"

到整数:

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

我目前正在循环字符串:

for char in time.characters {
}

但我不知道如何将 char 转换为 int。任何帮助将不胜感激。

【问题讨论】:

    标签: ios swift swift2


    【解决方案1】:

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

    【讨论】:

    • 这似乎是更“类似 Swift”的答案。
    • 这就是我最终使用的。谢谢!!
    • 不错的解决方案!
    • 简洁优雅!我为项目中需要的秒数添加了 let seconds = components[2]。
    【解决方案2】:

    使用String.componentsSeparatedByString 将time 字符串拆分为多个部分:

    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)
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 2016-08-20
        • 2011-04-22
        相关资源
        最近更新 更多