Convert Character to Int in Swift 2.0

Aaron picture Aaron · Jun 11, 2015 · Viewed 33.5k times · Source

I just want to convert a character into an Int.

This should be simple. But I haven't found the previous answers helpful. There is always some error. Perhaps it is because I'm trying it in Swift 2.0.

for i in (unsolved.characters) {
  fileLines += String(i).toInt()
  print(i)
}

Answer

Aaron Brager picture Aaron Brager · Jun 11, 2015

In Swift 2.0, toInt(), etc., have been replaced with initializers. (In this case, Int(someString).)

Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (Int?) instead of just an Int. The best thing to do is unwrap this optional using if let.

I'm not sure exactly what you're going for, but this code works in Swift 2, and accomplishes what I think you're trying to do:

let unsolved = "123abc"

var fileLines = [Int]()

for i in unsolved.characters {
    let someString = String(i)
    if let someInt = Int(someString) {
        fileLines += [someInt]
    }
    print(i)
}

Or, for a Swiftier solution:

let unsolved = "123abc"

let fileLines = unsolved.characters.filter({ Int(String($0)) != nil }).map({ Int(String($0))! })

// fileLines = [1, 2, 3]

You can shorten this more with flatMap:

let fileLines = unsolved.characters.flatMap { Int(String($0)) }

flatMap returns "an Array containing the non-nil results of mapping transform over self"… so when Int(String($0)) is nil, the result is discarded.