微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在SwiftUI / Swift中加载大量的静态数据

如何解决在SwiftUI / Swift中加载大量的静态数据

我要完成的工作是将大量的值数据加载到swiftUI中,以便我可以将其作为静态信息提供给应用程序。我有一个Excel文件,其中包含4000多个行,其中包含有关每个国家/地区的约20个经济数据。而且我计划在不久的将来再增加10,000行。我设法将整个数据转换为元组格式,这就是我目前拥有的:

var countryInfo:[(economicIndicator:String,country:String,year:String,dataValue:String)] = [ //100th line of code
    (economicIndicator: "GDP",country: "Afghanistan",year: "2018",dataValue: "$19.36 billion"),(economicIndicator: "Inflation.",year: "2019",dataValue: "2.3%"),(economicIndicator: "CPI",year: "2017",dataValue: "$1.014 billion")
    ...
    (economicIndicator: "GDP",dataValue:  "$31 billion"),dataValue: "255.29%"),country:"Afghanistan",dataValue: "$7 billion") //4117th line of code
]

以下是一个小型SwiftUI视图:

struct CountryStatistics: View {
    @State private var currentCountry = countryInfo.filter { $0.country == "Zimbabwe" }
    var body: some View{
        vstack{
            Text("country: \(self.currentCountry[0].country)")
            HStack{
                vstack(alignment: .leading){
                    ForEach(0..<currentCountry.count){ i in
                        Text("\(currentCountry[i].economicIndicator)")
                            .minimumScaleFactor(0.2)
                    }
                }.padding()
                vstack(alignment:.leading){
                    ForEach(0..<currentCountry.count){ i in
                        Text("\(currentCountry[i].dataValue)")
                            .minimumScaleFactor(0.2)
                    }
                }.padding()
            }
            HStack{
                Button("Change to Afghanistan"){
                    self.currentCountry = countryInfo.filter { $0.country == "Afghanistan" }
                }
                Button("Change to Zimbabwe"){
                    self.currentCountry = countryInfo.filter { $0.country == "Zimbabwe" }
                }
            }
        }.animation(.easeIn)
    }}

您可以想象,xCode尝试使用具有4000+值的元组运行时会大大减慢速度,即使让xCode尝试运行30分钟,我的应用程序也无法运行。没有错误,并且如果我使用约20行的元组对其进行测试,它将可以正常工作。我认为这是因为这不是应该使用元组的方式,这就是xCode无法运行的原因。我想尽力构建自己的第一个应用程序并将其发布到appStore,所以我认为元组可能是最简单的方法,但是我认为这不可能。

是否有更有效的方式将所有数据加载到我的应用程序中,或者使swift实际运行代码?我不想依赖在线API,因为我希望数据可供离线用户使用。

编辑-我也尝试过通过JSON进行操作,但是事情还是行不通,我认为这可能是因为JSON的自定义格式,因为我是手工制作的。这就是我遇到的问题,但在获得json解码器功能后仍然遇到问题,因此我留在元组中:

[{
    "country":"Afghanistan","facts":[{
        "GDP":"$19.36 billion","Inflation":"2.3%","CPI":"$1.014 billion",}]
},{
    "country":"Zimbabwe","facts":[{
        "GDP":"$31 billion","Inflation":"255.29%","CPI":"$7 billion",}]
}]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。