Home > Software design >  How to filter an array in swift?
How to filter an array in swift?

Time:08-31

I am getting the following as the response of an API,

[
    {
        "profileName": "indoor",
        "frequencies": [
            {
                "frequency": "200",
                "L": 120,
                "R": 150
            },
        ]
    },
    {
        "profileName": "outdoor",
        "frequencies": [
            {
                "frequency": "200",
                "L": 120,
                "R": 150
            },
        ]
    }
]

I need to filter this result based on profileName, need to access the frequency, L, and R and I want to show these in labels, I don't know how to filter the result. How to do that?

CodePudding user response:

1.create Codable structs to convert your JSON to swift

struct ResponseModel: Codable {
   let profileName: String
   let frequencies: [Frequency]
}

struct Frequency: Codable {
   let frequency: String
   let l, r: Int

enum CodingKeys: String, CodingKey {
    case frequency
    case l = "L"
    case r = "R"
}

}

2.convert

let decoder = JSONDecoder()

let response = try! decoder.decode(ResponseModel.self, from: jsonData)

3.an example of filtering data

let indoorFrequencies = response.filter{$0.profileName == "indoor"}.map{$0.frequencies}
  • Related