1

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?

1
  • If you want 1234 instead of 1,2,3,4 then you don't need an array for that. 1234 is a single int value. Commented Dec 16, 2014 at 9:09

3 Answers 3

4

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() {
        digits.append(digit)
    }

    return digits
})

if countElements(text) == digits.count {
    // all digits valid
} else {
    // has invalid digits
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, the first piece of code is enough because the user can only enter integers since I set the text field keyboard type to "Number Pad".
Yes, this is the right way to get characters from string.
1

Here is a much simpler solution for future users

let text : String = "12345"
var digits = [Int]()
for element in text.characters 
{
    digits.append(Int(String(element))!)
}

Comments

0

Convert String into [Int] extension - Swift Version

I put below extensions which allow you to convert String into [Int]. It's long version, where you can see what happen in each line with your string.

extension String {

    func convertToIntArray() -> [Int]? {

        var ints = [Int]()
        for char in self.characters {
            if let charInt = char.convertToInt() {
                ints.append(charInt)
            } else {
                return nil
            }
        }
        return ints
    }
}


extension Character {

    func convertToInt() -> Int? {
        return Int(String(self)) ?? nil
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.