Convert string array description to array

5 Solutions Collect From Internet About “Convert string array description to array”

You can do that by splitting array and filtering all elements that cannot be converted to Int.

 "[12,33,22,44]".componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "[,]")).filter{ $0.toInt() != nil }.map{ $0.toInt()! } // [12, 33, 22, 44]

You can

  • trim the [ and ] characters with stringByTrimmingCharactersInSet;
  • split it into an array of components separated by commas; and
  • trim whitespace around each item.

For example:

let array = [12,33,22,44];
let string = array.description;  // result is "[12, 33, 22, 44]", not "[12,33,22,44]"

let results = string
    .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
    .componentsSeparatedByString(",")
    .map { return $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }

Or if you want an array of integers instead of an array of strings:

let results = string
    .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
    .componentsSeparatedByString(",")
    .map { return $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).toInt()! }  // remove `!` if you're not assured that only integers will be present

A safe way of doing this is to encode the String as data then decode the data as JSON and finally downcast the result as an array of Ints:

let base = [12,33,22,44]
let source = base.description
if let data = source.dataUsingEncoding(NSUTF8StringEncoding) {
    if let arrayOfInts = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Int] {
        print(arrayOfInts) // [12, 33, 22, 44]
        print(arrayOfInts[1]) // 33
    }
}

Rob’s answer for Swift 2.2

let results = value
            .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
            .componentsSeparatedByString(",")
            .map { return Int($0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))!}  // remove `!` if you're not assured that only integers will be present

Swift 3 code:

let results = "[12,33,22,44]"
              .trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
              .components(separatedBy:",")

print("Result array: \(results)")