30

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)
}
1
  • I'm voting to close this question as off-topic because the question is related to old and unsupported version of a Swift compiler Jan 11, 2020 at 13:24

5 Answers 5

47

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.

2
  • Thanks so much! Everything is working, except fileLines is an Array of Ints for me. var fileLines: [Int] = [] (it says that fileLines cannot use +=)
    – Aaron
    Jun 11, 2015 at 3:57
  • 1
    You can use the append method, or do fileLines += [someInt] Jun 11, 2015 at 3:58
9

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.

3

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.

2
  • This seems way easier. Sep 27, 2015 at 22:17
  • 7
    chars cannot be both the new created constant and the parameter of Int. Jan 30, 2016 at 21:11
3

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]
3

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.