1

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)")
5
  • 1
    Where is the string comming from ? Commented Apr 20, 2016 at 0:36
  • My app uses Cordova, so this is a command coming from a Javascript interface. Commented Apr 20, 2016 at 0:37
  • 1
    Looks like JSON try using SwiftyJSON to parse it Commented Apr 20, 2016 at 0:37
  • @LeoDabus I could use SwiftyJSON but I am curious if theres a quick way built into swift where I can move directly to a string array from a string formatted as an array Commented Apr 20, 2016 at 0:38
  • 1
    There's stuff built in to Foundation, but not built into the Swift standard library as far as I know. Commented Apr 20, 2016 at 0:39

2 Answers 2

3

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

3 Comments

Interesting I've not seen this syntax before! Could you name what guard let data = source.dataUsingEncoding(NSUTF8StringEncoding), arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) is called? I'd like to read up on this
It's called a "guard statement" and you can read about it here: developer.apple.com/library/ios/documentation/Swift/Conceptual/… in the "Early exit" section of "Control Flow". It's an alternative to if let that lets you use the unwrapped value in the current scope. It's very convenient. :)
Very cool! Might want to update your answer to include the catch ;).
1

Agree with comments above, I'd probably use a JSON parser. Failing that (or if you can't for some reason), I do not know of any built-in way; you'd have to do it manually. I'd do something like:

extension String {
    func stringByTrimmingFirstAndLast() -> String {
        let startIndex = self.startIndex.successor()
        let endIndex = self.endIndex.predecessor()
        return self.substringWithRange( startIndex..<endIndex )
    }
}

let str = "[\"word1\",\"word2\"]"
let array = str
    .stringByTrimmingFirstAndLast()
    .componentsSeparatedByString(",")
    .map { string in
        return string.stringByTrimmingFirstAndLast()
    }

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.