Search code examples
arraysswiftnsarraynsdictionaryswift-dictionary

Creating array of string from the array of dictionaries in swift


I have JSON response as given below:

{
    "status": true,
    "data": [
        {
            "id": 2,
            "name": "demo",            
            "last_name": "test"
        },
        {
            "id": 6,                
            "name": "test",                
            "last_name": null
        },
        {
            "id": 15,
            "name": "test",                
            "last_name": null
        }
    ],
    "message": "List fetched successfully"
}

From the above response, I would like to create an array of strings which is a combination of values of the keys

name

and

last_name

from the above-given response. How can I achieve array of strings as given below:

["<name last_name>","<name last_name>","<name last_name>"]

Your help will be appreciated.


Solution

  • First you need to create your structs to decode the JSON (note that I'm only appending last_name if it's not nil):

    struct Model: Codable {
       let status: Bool
       let data: [DataEntry]
       let message: String
    }
    
    struct DataEntry: Codable {
       let id: Int
       let name: String
       let last_name: String?
    }
    

    Once you decode your JSON, you can obtain the array you want by using the map function:

    stringArray = decodedData.data.map { 
       var string = $0.name
       if $0.last_name != nil { 
          string.append(" ")
          string.append($0.last_name!)
       }
       return string
    }