How to convert a String (numeric) in a Int array in Swift

后端 未结 8 1434
鱼传尺愫
鱼传尺愫 2021-02-13 20:41

I\'d like to know how can I convert a String in an Int array in Swift. In Java I\'ve always done it like this:

String myString = \"123456789\";
int[] myArray = n         


        
相关标签:
8条回答
  • 2021-02-13 21:07
    let str = "123456789"
    let intArray = map(str) { String($0).toInt() ?? 0 }
    
    • map() iterates Characters in str
    • String($0) converts Character to String
    • .toInt() converts String to Int. If failed(??), use 0.

    If you prefer for loop, try:

    let str = "123456789"
    var intArray: [Int] = []
    
    for chr in str {
        intArray.append(String(chr).toInt() ?? 0)
    }
    

    OR, if you want to iterate indices of the String:

    let str = "123456789"
    var intArray: [Int] = []
    
    for i in indices(str) {
        intArray.append(String(str[i]).toInt() ?? 0)
    }
    
    0 讨论(0)
  • 2021-02-13 21:15

    @rintaro's answer is correct, but I just wanted to add that you can use reduce to weed out any characters that can't be converted to an Int, and even display a warning message if that happens:

    let str = "123456789"
    let intArray = reduce(str, [Int]()) { (var array: [Int], char: Character) -> [Int] in
        if let i = String(char).toInt() {
            array.append(i)
        } else {
            println("Warning: could not convert character \(char) to an integer")
        }
        return array
    }
    

    The advantages are:

    • if intArray contains zeros you will know that there was a 0 in str, and not some other character that turned into a zero
    • you will get told if there is a non-Int character that is possibly screwing things up.
    0 讨论(0)
提交回复
热议问题