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

21,611

Solution 1

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

Solution 2

You can use flatMap to convert the characters into a string and coerce the character strings into an integer:

Swift 2 or 3

let string = "123456789"
let digits = string.characters.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4

let string = "123456789"
let digits = string.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4.1

let digits = string.compactMap{Int(String($0))}

Swift 5 or later

We can use the new Character Property wholeNumberValue https://developer.apple.com/documentation/swift/character/3127025-wholenumbervalue

let digits = string.compactMap{$0.wholeNumberValue}

Solution 3

Swift 3

Int array to String

let arjun = [1,32,45,5]
    print(self.get_numbers(array: arjun))

 func get_numbers(array:[Int]) -> String {
        let stringArray = array.flatMap { String(describing: $0) }
        return stringArray.joined(separator: ",")

String to Int Array

let arjun = "1,32,45,5"
    print(self.get_numbers(stringtext: arjun))

    func get_numbers(stringtext:String) -> [Int] {
    let StringRecordedArr = stringtext.components(separatedBy: ",")
    return StringRecordedArr.map { Int($0)!}   
}

Solution 4

@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.
Share:
21,611
t0re199
Author by

t0re199

Java (Android, EE), Swift, Assembly, C, C#, Python, PHP, Javascript, Typescript (Angular). 23 yo Italian Computer Science Engineering Student.

Updated on July 26, 2020

Comments

  • t0re199
    t0re199 almost 4 years

    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 = new int[myString.lenght()];
    for(int i=0;i<myArray.lenght;i++){
       myArray[i] = Integer.parseInt(myString.charAt(i));
    }  
    

    Thanks everyone for helping!

  • Nate Cook
    Nate Cook about 9 years
    You have a loop in your loop—calling advance over and over like that is a bad idea, since you're making the program step through the string from the beginning each time.
  • Luca Angeletti
    Luca Angeletti about 8 years
    toInt() is no longer available in String in Swift 2.x.
  • leanne
    leanne almost 6 years
    Swift 4.1 deprecates .flatMap for this use case. Use .compactMap instead: let digits = string.compactMap{Int(String($0))}
  • leanne
    leanne almost 6 years
    Swift 4.1 deprecates .flatMap for this use case. Instead, use .compactMap: let intArray = string.components(separatedBy: "").compactMap { Int($0) }
  • Leo Dabus
    Leo Dabus almost 6 years
    @leanne this is wrong it would result in an array with a single element of the same value of the input [123456789]. The first method components(separatedBy: "") would result in a single string element ["123456789"]
  • leanne
    leanne almost 6 years
    I simply replaced the deprecated .flatMap with the new .compactMap, @LeoDabus. Both results are the same. As printed in Xcode's debug console: [123456789] and [123456789]. Note that I am not judging whether the result is appropriate for the original question, but simply remarking for anyone who comes here that .flatMap has been deprecated in favor of .compactMap in cases where one is attempting to achieve a result that removes nil values.
  • Mark Rotteveel
    Mark Rotteveel almost 4 years
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.