Convert Character to Int in Swift 2.0

35.3k views Asked by At

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

There are 5 answers

2
Aaron Brager On BEST ANSWER

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.

0
Declan McKenna On

Swift 4 solutions

To convert a Character to a String:

let digit = Int(String("1"))! 
//Don't force unwrap this if you're not 100% sure your character is a digit

Solution to OPs problem:

let fileLines = unsolved.compactMap{ Int(String($0) }
// fileLines = [1, 2, 3]
0
MiladiuM On

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.

2
Tuan Anh Vu On

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.

0
parametr On

In the latest Swift versions (at least in Swift 5) you don't need to do additional conversion to String.

Character has property wholeNumberValue which tries to convert a character to Int and returns nil if the character does not represent and integer.

let char: Character = "5"
if let intValue = char.wholeNumberValue {
    print("Value is \(intValue)")
} else {
    print("Not an integer")
}