Does anyone know the simplest way to convert an Array inside of a String to an actual Array without effecting any characters?
For Example:
var array: [String] = []
let myStr = "[\"Hello,\", \"World\"]"
// I would like 'array' to store: ["Hello,", "World"]
I thought it could be done with Array(myStr)
but that would only make an array of all the characters.
Help would be appreciated. Thank you.
You can decode it with JSONDecoder
, since it is a JSON.
Example below:
let myStr = "[\"Hello,\", \"World\"]"
let data = Data(myStr.utf8)
do {
let decoded = try JSONDecoder().decode([String].self, from: data)
print("Decoded:", decoded)
} catch {
fatalError("Error")
}
// Prints: Decoded: ["Hello,", "World"]
What is happening:
myStr
string is converted to Data
.[String]
- which is an array of strings.[String]
is then printed.We use a do-try-catch pattern to catch errors, such as incorrect format or data entered.