如何基于波斯字符在swift中对JSON进行排序

时间:2018-05-10 12:38:53

标签: ios json swift sorting swift4

我是swift的新手,我打算不用代码对包中的json文件进行排序,无论如何使用代码对文件进行排序,我想从“citname”中排序:“لومار”

json文件是:

{


    "data":[
        {
            "_id":1,
            "citproidint":4,
            "citname":"لومار"
        },
        {
            "_id":2,
            "citproidint":4,
            "citname":"ايوان"
        },
        {
            "_id":3,
            "citproidint":12,
            "citname":"آبعلی"
        },
        {
            "_id":4,
            "citproidint":25,
            "citname":"نيشابور"
        },
        {
            "_id":5,
            "citproidint":27,
            "citname":"سقز"
        }, 

        ]

}

... // 827 id在这个json文件中 并且对于这个json文件中的每个块我都像这样解析,一切都很好但是我想用它在我的pickerview中排序然后我需要保存已排序的模态

guard let path = Bundle.main.path(forResource: "citybig", ofType: "json") else { return }
// city Text  file:// ...
let url = URL(fileURLWithPath: path)
do {
    // data explained in bytes
    let data = try Data(contentsOf: url)
    // we get the json file text
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    // put json in nsdictinary so we can access each index and person sooo ... id and more

    for (key,value) in json as! NSDictionary {
        if (key as! String) == "data" {
            let value2 = value.s
            for each in value as! [[String: Any]] {
        let singleCityModal = cityModal()
    for (key,value) in each {
        switch key {
        case "_id" :
            singleCityModal.id = value as? Int
        case "citproidint" :
            singleCityModal.citproidint = value as? Int
        case "citname" :
            singleCityModal.citname = value as? String
        default:
            break
            }
        } 
   cityFirstModal.append(singleCityModal)
    }

    cityFinalModal.append(contentsOf: cityFirstModal)

1 个答案:

答案 0 :(得分:3)

您解析数据的方法非常奇怪,在Swift 4中,有一种更方便的方法,即df_with_more_zeros = df.apply(lambda x: x.replace(to_replace=x[x!=0].sample(10), value=0), axis=1) 协议。

您需要两个结构:

Decodable

并且解析JSON的代码变得更短(更有效)

struct CityData : Decodable {
    private enum CodingKeys: String, CodingKey { case cities = "data"}

    let cities : [City]
}

struct City : Decodable {
    private enum CodingKeys: String, CodingKey { case id = "_id", citproidint, name = "citname"}

    let id, citproidint: Int
    let name : String
}

用于感叹号。由于(不可变)文件位于捆绑软件中,因此代码不得崩溃。如果是这样,您就犯了一个设计错误。

这仅仅是对let url = Bundle.main.url(forResource: "citybig", withExtension: "json")! let data = try! Data(contentsOf: url) let cityData = try! JSONDecoder().decode(CityData.self, from: data) 进行城市排序的另一行

citproidint

我对波斯语不熟悉,但是如果您想按let sortedCities = cityData.cities.sorted(by: {$0.citproidint < $1.citproidint}) 进行排序,选择器name可能会完成

localizedStandardCompare