1

I have the following code:

var data = [12,33,22,44];
var a =  data.description;  // results is "[12,33,22,44]"
var new = Array(a); // result is ['[','1'.  not [12,33,22,44]

Aside splitting 'a' and iterating the result, There is a fastest way to convert a string to an array ?

Thanks

2
  • 2
    actually the variable data is an array. Commented Aug 14, 2015 at 13:14
  • I think he wants a solution for a scenario where only the description of the array is available. Commented Aug 14, 2015 at 13:17

5 Answers 5

4

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

Comments

3

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

Comments

2

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
    }
}

Comments

1

Swift 3 code:

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.