我有一个留言板,在这个留言板中,从数据库中检索到的项目按最新到最旧的顺序排序。但是,在按时间顺序加载结构之后,我希望第一项成为当前用户的消息,而不管它是否是最新的消息。我试着用下面的函数来做这件事,但结果是按顺序对用户名进行排序。
结构代码
struct MessageBoard: Equatable{
var username: String! = ""
var messageImage: UIImage! = nil
var messageId: String! = ""
var timeSince: String! = ""
init(username: String, messageId: UIImage, messageId: String, timeSince: String) {
self.username = username
self.messageImage = messageImage
self.messageId = messageId
self.timeSince = timeSince
}
static func == (lhs: MessageBoard, rhs: MessageBoard) -> Bool {
return lhs.username == rhs.username
}
}
var messageBoardData = [MessageBoard]()排序码
self.messageBoardData.sort { (lhs, rhs) in return lhs.username > rhs.username }
发布于 2020-06-14 07:26:01
传递给sort的闭包应该在lhs, rhs按所需顺序返回时返回true。使用这个逻辑,我们可以编写一个修改过的闭包版本,检查用户名是否是当前用户:
self.messageBoardData.sort {
lhs, rhs in
if lhs.username == currentUsername { // or however you check the current user...
return true // the current user should always be sorted before everything
} else if rhs.username == currentUsername {
return false // the current user should not be sorted after anything
} else {
return lhs.username > rhs.username // do the normal sorting if neither is the current user
}
}https://stackoverflow.com/questions/62369448
复制相似问题