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)}
print(arrayOfInts)
Try this:
var test = "[1, 0, 4]"
test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]
flatMap would be far nicer than force unwrapping the Int? in the map ;) That way you can filter out any elements that can't be represented as numbers without crashing.
let testConverted = test.characters.flatMap({String($0)}).flatMap({Int($0)})"[10, 50, 40]"goes to[1, 0, 5, 0, 4, 0]. Although I see no reason to useflatMaptwice there, you could just dolet testConverted = test.characters.flatMap{Int(String($0))}