首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift中只洗牌结构的一部分

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

Stack Overflow用户
提问于 2020-06-14 07:05:30
回答 1查看 57关注 0票数 2

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

结构代码

代码语言:javascript
复制
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 }

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-14 07:26:01

传递给sort的闭包应该在lhs, rhs按所需顺序返回时返回true。使用这个逻辑,我们可以编写一个修改过的闭包版本,检查用户名是否是当前用户:

代码语言:javascript
复制
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
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62369448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档