I have this variable
var = "[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]"
how I can convert it to be an array
[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]
Your string contains the JSON representation of an array with
string elements. You can convert it to a Swift [String] array
using the JSONSerialization class:
let jsonString = "[\"foo\", \"bar\", \"baz\"]"
print("JSON:", jsonString)
let jsonData = jsonString.data(using: .utf8)! // Conversion to UTF-8 cannot fail.
if let array = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String] {
// `array` has type `[String]`.
// Let's dump the array for demonstration purposes:
print("\nArray:")
for (idx, elem) in array.enumerated() {
print(idx, elem)
}
} else {
print("malformed input")
}
Output:
JSON: ["foo", "bar", "baz"] Array: 0 foo 1 bar 2 baz