convert user input to array of Ints in swift

爷,独闯天下 提交于 2019-12-23 02:31:35

问题


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:


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
}



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/27500957/convert-user-input-to-array-of-ints-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!