Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Date String to Int Swift

Tags:

ios

swift

swift2

I am trying to convert the string:

let time = "7:30"

to integers:

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

I am currently looping through the string:

for char in time.characters {
}

But I cannot figure out how to convert a char to an int. Any help would be greatly appreciated.

like image 333
brl214 Avatar asked Dec 19 '22 23:12

brl214


2 Answers

Answers by @alex_p and @mixel are correct, but it's also possible to do it with Swift split function:

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]
like image 99
egor.zhdan Avatar answered Jan 21 '23 20:01

egor.zhdan


Use String.componentsSeparatedByString to split time string to parts:

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
    }
}

If you do not want to import Foundation you can split time string to parts with:

let timeParts = time.characters.split(":").map(String.init)
like image 25
mixel Avatar answered Jan 21 '23 20:01

mixel