Sarita Sarita - 6 months ago 5x
Swift Question

Converting a String to an Int Array

I've that type of String for example:

var test:String = "[1, 0, 4]";

And I need to convert it to an array of Int:

var testConverted:[Int] = [ 1, 0, 4 ];


You'll want to trim off the start and end brackets by using stringByTrimmingCharactersInSet, then get the array of string elements by using componentsSeparatedByString. Then you can finally use flatMap to create an array of integers from this.

For example:

let yourString = "[1, 0, 4]"

// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")

// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}