在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 }

清扫器

您传递给的闭包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
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章