Aggressor Aggressor - 2 years ago 112
Swift Question

Swift Convert A String-As-An-Array, To An Array Of Strings

I have a string:


And I want a simple way to convert it to an actual

All the other questions I could dig up on there were about converting int strings to arrays.

I tried doing

Array(arrayLiteral: "["word1","word2"]")

But I get


Manually cleaning up the edges and removing the slashes seems like I'm doing something very wrong.

I'm curious if there's a simple way to convert a an array of strings as a string into an array of strings.

i.e. Convert

Solution (Thanks to @Eric D)

let data = stringArrayString.dataUsingEncoding(NSUTF8StringEncoding)

var stringsArray:[String]!

stringsArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String]
} catch

print("Array is \(stringsArray)")

Answer Source

Encode your "string array" to data, then decode this data as JSON to a Swift Array.

Like this, for example:

let source = "[\"word1\",\"word2\"]"

guard let data = source.dataUsingEncoding(NSUTF8StringEncoding),
    arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else {

print(arrayOfStrings)  // ["word1", "word2"]
print(arrayOfStrings[1])  // "word2"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download