Search code examples
swift4

Array (Inside of a String) Conversion, Swift 4


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.


Solution

  • 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.