0

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.

1 Answer 1

1

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:

  1. Your myStr string is converted to Data.
  2. This data is then decoded as [String] - which is an array of strings.
  3. The decoded data of type [String] is then printed.

We use a do-try-catch pattern to catch errors, such as incorrect format or data entered.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.