1

Does Swift provide a way to convert a raw String like this

"[\"John\",\"Anna\",\"Tom\"]"

to an Array of strings ([String])?

I've looked for a way to do it over StackOverflow, but in that specific way, I could not find an answer :/

2 Answers 2

4

On Swift 4 and later, use JSONDecoder:

let rawString = "[\"John\",\"Anna\",\"Tom\"]"
let jsonData = rawString.data(using: .utf8)!
let strings = try JSONDecoder().decode([String].self, from: jsonData)
Sign up to request clarification or add additional context in comments.

Comments

0

Code Different answer is probably a recommended way to do it nowadays (Swift 4+).

For reference, here is a classic way to do the same, compatible with older Swift versions:

let rawString = "[\"John\",\"Anna\",\"Tom\"]"
let jsonData = rawString.data(using: .utf8)!
let strings = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String] ?? []

According to Itai Ferber, JSONDecoder uses JSONSerialization under the hood, so it should do pretty much the same as Code Different answer.

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.