gpt4 book ai didi

arrays - 使用 JSON 对 Swift 数组进行排序

转载 作者:行者123 更新时间:2023-11-28 15:52:40 30 4
gpt4 key购买 nike

数据:尝试从 JSON 获取数据

具有在 Playground 上运行的 Swift 代码

 var roadWayStatusArray = [AnyObject]()


let url = URL(string: "http://od.moi.gov.tw/data/api/pbs")
let data = try? Data(contentsOf: url!)
let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if let results = json as? [String : AnyObject] {
if let result = results["result"] as? [[String : AnyObject]] {
for data in result {
let happendate = data["happendate"] as? String
roadWayStatusArray.append(data as AnyObject!)
}
}
}

我已经尝试使用 roadWayStatusArray.sort(by: >)Xcode 报告我 Ambiguous reference member '>'

如何按 hapendatehappentime 创建排序

最佳答案

您的 roadWayStatusArray 是一个 AnyObject 数组。没有为 AnyObject 定义的 > 运算符。

roadWayStatusArray 中的对象实际上是字典,如下所示:

{
UID = "10602090007-0";
areaNm = "\U4e2d\U5c71\U9ad8\U901f\U516c\U8def-\U570b\U9053\Uff11\U865f";
comment = "\U5317\U4e0a.\U4e2d\U58e2\U670d\U52d9\U5340 \U51fa\U53e3\U531d\U9053\U4e2d \U53f3\U5074 \U5c0f\U5ba2\U8eca\U505c\U653e\Uff0c\U99d5\U99db\U7591\U4f3c\U7761\U8457\U4e86";
direction = "\U5317\U4e0a";
happendate = "2017-02-09";
happentime = "01:08:00.0000000";
modDttm = "2017-02-09 01:15:43.603";
region = N;
road = "";
roadtype = "\U5176\U4ed6";
srcdetail = "\U71b1\U5fc3\U807d\U773e";
x1 = "121.73558";
y1 = "25.12263";
}

您需要使用确定排序顺序的闭包来调用 sort(by:)。例如,如果您想按 happendate 排序,然后按 happentime 排序:

roadWayStatusArray.sort(by: { (lhsAny, rhsAny) -> Bool in
let lhs = lhsAny as? [String: AnyObject]
let rhs = lhsAny as? [String: AnyObject]
let lhsKey = (lhs?["happendate"] as? String ?? "", lhs?["happentime"] as? String ?? "")
let rhsKey = (rhs?["happendate"] as? String ?? "", rhs?["happentime"] as? String ?? "")
return lhsKey < rhsKey
})

关于arrays - 使用 JSON 对 Swift 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42119742/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com