Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 584
t0re199 Avatar asked Feb 19 '15 16:02

t0re199


1 Answers

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)
}
like image 88
rintaro Avatar answered Oct 13 '22 21:10

rintaro