我希望在tableView中对数据/数组的创建日期进行排序。我没有任何代码来支持这个,但我有来自数据库的单元格和图像的代码。
Database.database().reference().child("Projects").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject]
{
let project = Project(dictionary: dictionary)
self.ProjectsArray.append(project)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
else
{
print("fucked ")
}
self.FilterdProjectsArray = self.ProjectsArray
}, withCancel: nil)
数据库
答案 0 :(得分:0)
您只需添加一行:
self.ProjectsArray.append(project)
self.ProjectsArray = self.ProjectsArray.sorted { (lhs, rhs) in lhs.timestamp < timestamp }
其中date
是Project
对象
您可以将Optional
扩展为符合Comparable
,但更简单的处理方式可能是:
self.ProjectsArray = self.ProjectsArray.sorted { (lhs, rhs) in
let lTimestamp = lhs.timestamp ?? NSNumber(integerLiteral: 0)
let rTimestamp = rhs.timestamp ?? NSNumber(integerLiteral: 0)
return lTimestamp < rTimestamp
}
事实证明,NSNumbers并不具有可比性。看起来您需要使用Int
或Double
,对数据更有意义(您使用的是整数还是浮点数?
self.ProjectsArray = self.ProjectsArray.sorted { (lhs: Project, rhs: Project) in
let lTimestamp: Int
if let lNum = lhs.timestamp {
lTimestamp = Int(lNum)
} else {
lTimestamp = 0
}
let rTimestamp: Int
if let rNum = rhs.timestamp {
rTimestamp = Int(rNum)
} else {
rTimestamp = 0
}
return lTimestamp < rTimestamp
}