Peter71 Peter71 - 5 months ago 6x
Swift Question

Swift: String to ints without special function

I'm searching for a build-in function for converting a string like
"01092030" (format "[[dd]hh]mmss") to four individual integers.

  • dd => 01

  • hh => 09

  • mm => 20

  • ss => 30

dd and hh are optional. If missing they should be 0. I could do it by by developing a special function, but I like to use something like a regular expression.


I don't see the point of your "build-in function" or "regular expression" requirements, but whatever...

let s = "092030" as NSString
let pattern = "\\d\\d"
let reg = try! NSRegularExpression(pattern: pattern, options: [])
let matches = reg.matchesInString(s as String, options: [], range: NSMakeRange(0, s.length))
var result = {s.substringWithRange($0.range)}
while result.count < 4 {
    result.insert("0", atIndex: 0)
// result is: ["0", "09", "20", "30"]

I'm also a little unclear on your output requirements. On the one hand, you say you want four "individual integers". But "09" is not an integer; it's a string representing an integer. So it seems to me that you actually want strings. If so, then result is the desired result. If not, then you need one more step:

let result2 ={Int($0)!}
// result2 is: [0, 9, 20, 30]