Convert Character to Int in Swift 2.0

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.


This is a bit of improvisational trick I came up with. Since it can be tricky to convert Character to Int, but you can easily convert String to Int do this :

fileLines = Int(String(i))!

of course this is not very well optimized but for cases like yours it can do the trick.


Actually. A simpler way is to convert String to Int in Swift 2.o is:

let chars = Int(chars)

Not sure if this is what you're trying for...But you can easily apply this to your loop, of course.