harinder rana
harinder rana

Reputation: 107

How to fetch data from array of Dictionary - swift

How can I fetch data from this array? Here there is an array which contains some key value pairs, and some keys contain an array of dictionary.

 var dataArray = [
                ["teamName":"Arsenal",
                  "image":"imageName",
                  "nextMatch":"in 2 days",
                  "matches":[
                                ["oppositeTeam":"teamName",
                                 "matchTimings":"121212",
                                 "matchId":"ID 213432"],
                                ["oppositeTeam":"teamName",
                                 "matchTimings":"121212",
                                 "matchId":"ID 213432"]
                            ],
                  "fixtures":[
                                ["oppositeTeam":"teamName",
                                 "oppositeTeamScore":"7",
                                 "HomeTeamScore":"4",
                                 "HomeTeamCards":"True",
                                 "oppositeTeamCards":"false",
                                 "fixturesId":"ID 213432"],

                            ]
    ],["teamName":"Chelsea",
        "image":"imageName",
       "nextMatch":"in 2 days",
       "matches":[["oppositeTeam":"teamName",
                   "matchTimings":"121212",
                   "matchId":"ID 213432"],["oppositeTeam":"teamName",
                                           "matchTimings":"121212",
                                           "matchId":"ID 213432"]
        ],"fixtures":[["oppositeTeam":"teamName",
                       "oppositeTeamScore":"7",
                       "HomeTeamScore":"4",
                       "HomeTeamCards":"True",
                       "oppositeTeamCards":"false",
                       "fixturesId":"ID 213432"],["oppositeTeam":"teamName",
                                                  "oppositeTeamScore":"7",
                                                  "HomeTeamScore":"4",
                                                  "HomeTeamCards":"True",
                                                  "oppositeTeamCards":"false",
                                                  "fixturesId":"ID 213432"]
        ]
    ],["teamName":"India",
        "image":"imageName",
       "nextMatch":"null",
       "matches":[],
       "fixtures":[]
    ]]

I tried but I was unable to fetch data from this array.

Upvotes: 2

Views: 9555

Answers (4)

Shubham Bakshi
Shubham Bakshi

Reputation: 572

You need to use a Model like this

struct Team {
    let teamName:String
    let image:String
    let nextMatch:String
    let matches:[Match]?
    let fixtures:[Fixture]?
}

struct Match {
    let oppositeTeam:String
    let matchTimings:String
    let matchId:String
}

struct Fixture {
    let oppositeTeam:String
    let oppositeTeamScore:String
    let HomeTeamScore:String
    let HomeTeamCards:String
    let oppositeTeamCards:String
    let fixturesId:String
}

Next you need to learn about Codeable in swift for which I have attached an article below

Codeable Tutorial in swift

Upvotes: 4

HAK
HAK

Reputation: 2081

Here is how you can access the arrays/dictionaries defined in your dataArray:

    // To access team object at zero index
    if let team = dataArray[0] as? [String: Any] {
        print("Team: \(team["teamName"])")

        // To access matches array of team object at zero index
        if let matches = team["matches"] as? [[String: Any]] {
            print( matches)

            // To access first match
            if let match = matches.first {
                print(match)
            }
        }

        // Similar to matches access fixtures
        if let fixtures = dataArray[0]["fixtures"] as? [[String: Any]] {
            print(fixtures)

            // To access first fixture
            if let fixture = fixtures.first {
                print(fixture)
            }
        }
    }

This is ok if you are just prototyping. If you plan to extend this into an actual app creating separate models is the best approach.

You can have a Team model that can contain team name, image and matches and fixtures. For matches you can create a model with matche information in it. Similarly you can create a model for fixtures as well. Your Team class will then contain arrays of Match and Fixture classes like this:

var matches: [Match]
var fixtures: [Fixture]

and your dataArray will be of type

var dataArray: [Team]

Upvotes: 3

Sarabjit Singh
Sarabjit Singh

Reputation: 1824

You can fetch data from your Array like this:

for attributesObj in dataArray{
      let dicFrmArray = attributesObj as! NSDictionary

       if ((dicFrmArray["teamName"] as? NSNull) == nil && dicFrmArray["teamName"] != nil){
     print(dicFrmArray[teamName"])

       }
}

Upvotes: 1

Viren Malhan
Viren Malhan

Reputation: 115

Create model for your data using Codable. Parse the data in model using JSON decoder. Then you can use your model wherever you want.

For JSON parsing, you can refer this tutorial:- https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

Upvotes: 2

Related Questions