2

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 ];
3
  • 1
    You can skip trimming and stuff and go like this let testConverted = test.characters.flatMap({String($0)}).flatMap({Int($0)}) Commented Apr 21, 2016 at 10:19
  • @Whirlwind That's pretty neat, but assumes single digit numbers, which may not be what OP wants. For example "[10, 50, 40]" goes to [1, 0, 5, 0, 4, 0]. Although I see no reason to use flatMap twice there, you could just do let testConverted = test.characters.flatMap{Int(String($0))} Commented Apr 21, 2016 at 11:04
  • @originaluser2 You are right, thanks, I was hasty and wasn't thinking about multiple digit numbers, but rather concentrated on OP's example. Commented Apr 21, 2016 at 11:21

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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]

2 Comments

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.
Thanks for your advice :D.