4

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.

Wouter
  • 1,568
  • 7
  • 28
  • 35
brl214
  • 527
  • 1
  • 6
  • 16

3 Answers3

5

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)
mixel
  • 25,177
  • 13
  • 126
  • 165
5

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]
egor.zhdan
  • 4,555
  • 6
  • 39
  • 53
1

You can split string by : character and then convert results to Int:

let timeStringArray = time.componentsSeparatedByString(":")
if timeStringArray.count == 2 {
   hour = timeStringArray[0].toInt
   minutes = timeStringArray[1].toInt()
}
Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22