0

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\"]

2 Answers 2

3

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

Comments

-2

Here, try this:

var input = "[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]"
let components = input.trimmingCharacters(in: ["\"", "[", "\"", "]"]).components(separatedBy: "\", \"")

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.