Iacopo Boccalari Iacopo Boccalari - 1 month ago 8x
iOS Question

convert user input to array of Ints in swift

I'm trying to make a simple iOS game to learn programming in swift.
The user inputs a 4 digits number in a text field (keyboard type number pad if that matters) and my program should take that 4 digits number and put each digit in an array.
basically I want something like

userInput = "1234"

to become

inputArray = [1,2,3,4]

I know converting a string to an array of characters is very easy in swift

var text : String = "BarFoo"
var arrayText = Array(text)
//returns ["B","a","r","F","o","o"]

my problem is I need my array to be filled with Integers, not characters.
If I convert the user input to an Int, it becomes a single number so if user enters "1234" the array gets populated by [1234] and not [1,2,3,4]

So I tried to treat the user input as a string, make an array of its characters and, then loop through the elements of that array, convert them to Ints and put them into a second array, like:

var input : String = textField.text
var inputArray = Array(input)
var intsArray = [Int]()

for var i = 0; i < inputArray.count ; i++ {
intsArray[i] = inputArray[i].toInt()

but it doesn't compile and gives me the error:
'Character' does not have a member named 'toint'

What am I doing wrong?


You could use:

let text : String = "123a"
let digits = Array(text).map { String($0).toInt()! }
// Crash if any character is not int

But it will crash if input is not valid.

You can validate by checking the result of toInt():

let text : String = "1234"
var digits = Array(text).reduce([Int](), combine: { (var digits, optionalDigit) -> [Int] in
    if let digit = String(optionalDigit).toInt() {

    return digits

if countElements(text) == digits.count {
    // all digits valid
} else {
    // has invalid digits