用Int排序数组

时间:2019-06-11 11:47:33

标签: arrays swift firebase sorting

我想将时间戳最大的数组排序为时间戳最小的数组。首先,我想从Firebase提取所有数据,并将其添加到数组中,当获取所有数据时,我想对数组进行排序。当我尝试执行此操作时,将在第posts.sort(by: {$0.timestamp > $1.timestamp})行出现此错误:

  

二元运算符'>'不能应用于两个'Int?'操作数

这是我的代码:

var posts: [Post] = []

Api.MyPosts.fetchMyPosts(userId: self.userId) { (key) in
     Api.Post.observePost(withId: key, completion: {
         post in
         self.posts.insert(post, at: 0)
         self.tableView.reloadData()
      })        
      posts.sort(by: {$0.timestamp > $1.timestamp})       
 }

有人知道我如何解决此错误并将时间戳记保持为整数吗?

1 个答案:

答案 0 :(得分:0)

您需要unwrap timestamp,因为它是一个optional Int值,即

posts.sort {
    guard let t1 = $0, let t2 = $1 else {
        return false
    }
    return t1 > t2
}
相关问题