Aggressor Aggressor - 7 months ago 38
Swift Question

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

I have a string:

"["word1","word2"]"


And I want a simple way to convert it to an actual
[String]
.

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

["[\"word1\",\"word2\"]"]


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
"["word1","word2"]"
to
["word1","word2"]


Solution (Thanks to @Eric D)

let data = stringArrayString.dataUsingEncoding(NSUTF8StringEncoding)

var stringsArray:[String]!

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

print("Array is \(stringsArray)")

Answer

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 {
        fatalError()
}

print(arrayOfStrings)  // ["word1", "word2"]
print(arrayOfStrings[1])  // "word2"
Comments