Search code examples
iosarraysswiftparsingdecoder

Parsing an array with separators into key-values


I am trying to parse an array safely to key-values using Swift 5. Here's an example -

["BirthDate=1976-09-11", "Name=Smith", "Status=Alive"]

or, maybe go with a 2D array if it helps after using split(separator: "=") on above -

[["BirthDate", "1976-09-11"], ["Name", "Smith"], ["Status", "Alive"]]

Now, this becomes an Array<Substring>. I have thought of Decodable and converting this array into a dictionary, but it did not lead me anywhere.


Solution

  • You can use reduce(into:_:):

    let array = ["BirthDate=1976-09-11", "Name=Smith", "Status=Alive"]
    
    let dictionary = array.reduce(into: [String: Any]()) { (result, current) in
        let separated = current.components(separatedBy: "=")
        guard separated.count == 2 else { return }
        result[separated[0]] = separated[1]
    }
    

    Output:

    $> ["Status": "Alive", "Name": "Smith", "BirthDate": "1976-09-11"]
    

    EDIT: As stated by @Leo Dabus, first line can be written let dictionary = array.reduce(into: [:]) { ... }, then dictionary will be a [AnyHashable : Any], or it can be let dictionary = array.reduce(into: [String: String]()) { ... } and dictionary will be a [String: String]