【问题标题】:How to fetch data from array of Dictionary - swift如何从字典数组中获取数据 - swift
【发布时间】:2018-11-12 06:43:53
【问题描述】:

如何从这个数组中获取数据? 这里有一个包含一些键值对的数组,一些键包含一个字典数组。

 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":[]
    ]]

我试过了,但我无法从这个数组中获取数据。

【问题讨论】:

  • 你能显示代码吗?你尝试了什么,最终得到了什么。
  • 请添加一些您尝试过的代码。

标签: ios arrays swift dictionary multidimensional-array


【解决方案1】:

你需要使用这样的模型

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
}

接下来你需要快速了解Codeable,我在下面附上了一篇文章

Codeable Tutorial in swift

【讨论】:

  • 好。显示使用示例可能会更好。
【解决方案2】:

以下是访问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)
            }
        }
    }

如果您只是进行原型设计,这没关系。如果您打算将其扩展到实际应用程序中,则创建单独的模型是最好的方法。

您可以拥有一个团队模型,其中可以包含团队名称、图像以及比赛和赛程。对于匹配,您可以创建一个包含匹配信息的模型。同样,您也可以为固定装置创建模型。然后,您的 Team 类将包含 Match 和 Fixture 类的数组,如下所示:

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

而您的dataArray 将是

类型
var dataArray: [Team]

【讨论】:

  • 总是乐于为 SO 提供帮助。如果我的回答解决了您的问题,请接受我的回答。
  • 在这种情况下我们如何迭代 dataArray [ ] @HAK
  • 迭代使用for循环:for team in dataArray { print("Team: \(team["teamName"])") }
  • 抱歉,我问的是“matches”和“fixtures”键中的数据
  • 由于fixture[String: Any] 类型的字典,您可以访问像fixture["oppositeTeam"] 这样的键
【解决方案3】:

使用 Codable 为您的数据创建模型。使用 JSON 解码器解析模型中的数据。然后,您可以在任何地方使用您的模型。

对于 JSON 解析,你可以参考这个教程:- https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

【讨论】:

  • 数据不是来自 API,它只是一个数组
  • 好主意 - 该数据在示例和定义中看起来确实非常接近 JSON。如果您分享how the array could be further transformed to JSON,此解决方案可能会起作用。该模型也将更可靠且抗断裂。只是需要更多细节......
  • 是的,它是我现在使用的 JSON 的替代品,因为我是 swift 编程新手。
【解决方案4】:

你可以像这样从你的数组中获取数据:

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

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

       }
}

【讨论】:

  • 强制展开并且 NS 对象在这一点上对于 swift 来说有点刺耳。我认为 if-let 或 guard 语句以及将数据保存为 Swift 对象会更好地为 OP 服务。
  • @TommieC。感谢您纠正我......我会更新这个:)
猜你喜欢
  • 1970-01-01
  • 2017-09-03
  • 2018-12-04
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多