早上好, 我一直在关注优秀iOS Apps With REST APIs书中的示例,并使用Alamofire和SwiftyJSON。我在书中没有看到的一件事是你如何将传入的json对象排序为特定的顺序,例如。日期。我在下面粘贴的代码可以很好地用于拉入json对象,但据我所知,它们会被created_by自动排序。我想按照不同的顺序排序,假设我的班级被称为蔬菜,并且有一个名称属性,以便我可以按以下方式排序:
.sort { $0.name < $1.name }
我将从Vegetable.swift中的Vegetable类开始
class Vegetable: ResponseJSONObjectSerializable {
var id: Int?
var name : String?
var date: NSDate?
}
在我的JSONSerializer文件中,我有以下内容,我不确定我是否希望直接在此处更改订单,因为我希望每次调用都更加灵活。
public func responseArray<T: ResponseJSONObjectSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
let serializer = ResponseSerializer<[T], NSError> { request, response, data, error in
guard error == nil else {
return .Failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .Success(let value):
let json = SwiftyJSON.JSON(value)
var objects: [T] = []
for (_, item) in json {
if let object = T(json: item) {
objects.append(object)
}
}
return .Success(objects)
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: serializer, completionHandler: completionHandler)
}
然后,在我的APIManager中,我有以下功能
func getAllVegetables(completionHandler: (Result<[Vegetable], NSError>) -> Void) {
Alamofire.request(VegetableRouter.GetVegetables())
.responseArray { (response:Response<[Vegetable], NSError>) in
completionHandler(response.result)
}
}
最后,填写我的tableview:
func loadVegetables() {
self.isLoading = true
VegetablesAPIManager.sharedInstance.getAllVegetables() {
result in
self.isLoading = false
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
guard result.error == nil else {
print(result.error)
// TODO: Display Error
return
}
if let fetchedVegetables = result.value {
self.vegetables = fetchedVegetables
for vegetable in fetchedVegetables {
// Nothing here at the moment
}
}
self.tableView.reloadData()
}
}
我感谢任何帮助,谢谢!
答案 0 :(得分:4)
由于您具有NSDate属性,因此可以使用NSDate的compare
方法进行排序。
let sorted = result.value.sort { $0.date.compare($1.date) == .OrderedAscending }