简体   繁体   中英

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.

ie 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)")

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM