2

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.

2
  • Can you show the code? What you tried and what you ended up getting. Commented Nov 12, 2018 at 6:47
  • Please add some code that you tried . Commented Nov 12, 2018 at 6:48

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good. Might be even better to show a sample of usage.
3

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]

5 Comments

Always happy to help on SO. If my answer solved your problem please accept my answer.
how we can iterate dataArray [ ] in this case @HAK
To iterate use for loop: for team in dataArray { print("Team: \(team["teamName"])") }
sorry i was asking about data inside "matches" and "fixtures" key
Since fixture is a dictionary of type [String: Any] you can access a key like fixture["oppositeTeam"]
2

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

3 Comments

data is not coming from API, it just an array
Good idea - That data does look very close to JSON in both sample and definition. This solution could work if you share how the array could be further transformed to JSON. The model would also be more reliable and resistant to breaking. Just need a bit more detail...
yes, its an alternate to JSON i am using for now as i am new in swift programming.
1

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"])

       }
}

2 Comments

Force unwrapping and the NS objects are a bit jarring for swift at this point. I'd think if-let or guard statements together with keeping the data as Swift objects would better serve the OP.
@TommieC. Thanks for correcting me... I will update this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.