vip*_*per 2 arrays dictionary ios swift swift4
这是我的NSObject类
class CustomDate: NSObject {
var quarter: Int!
var day: String!
var month: String!
var db: String!
var long: String!
var unix: Int!
init(quarter: Int, day: String, month: String, db: String, long: String, unix: Int) {
super.init()
self.quarter = quarter
self.day = day
self.month = month
self.db = db
self.long = long
self.unix = unix
}
}
Run Code Online (Sandbox Code Playgroud)
我创建的用于存储CustomDate的变量
var dates = [CustomDate]()
Run Code Online (Sandbox Code Playgroud)
我从字典中的json中以6个键值对获取数据,我想要的是,因为您可以看到下面的照片正在打印日期和月份。但是我需要按升序(或降序)对json数据进行排序。我该怎么做,这是我的代码。我正在使用alamofire来获取数据,并创建了一个NSObject类来存储数据
func apiData() {
Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as? [String: Any] else { return }
guard let data = json["data"] as? [String: Any] else { return }
for (_, value) in data {
let dateValue = value as! [String: Any]
let date = CustomDate(quarter: dateValue["quarter"] as! Int,
day: dateValue["day"] as! String,
month: dateValue["month"] as! String,
db: dateValue["db"] as! String,
long: dateValue["long"] as! String,
unix: dateValue["unix"] as! Int)
self.dates.append(date)
}
print(self.dates)
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如照片

要按数字顺序比较字符串,请使用localizedStandardCompare类似于Finder中的排序
dates.sort(by: {$0.month.localizedStandardCompare($1.month) == .orderedAscending})
Run Code Online (Sandbox Code Playgroud)
或compare选择numeric
dates.sort(by: {$0.month.compare($1.month, options: .numeric) == .orderedAscending})
Run Code Online (Sandbox Code Playgroud)
最好的解决方案可能是声明month为Int。