提问者:小点点

在Swift中只洗牌结构的一部分


我有一个留言板,其中的项目是从数据库检索时按最新到最早排序的。 但是,在按时间顺序加载结构之后,我希望第一项是当前用户的消息,而不管它是否是最新的消息。 我试着用下面的函数做了一下,但结果显示它按顺序对用户名进行了排序。

结构代码

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}


共1个答案

匿名用户

LHS,RHS按所需顺序排列时,传递给sort的闭包应返回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
    }
}