【问题标题】:Only shuffle part of a struct in Swift仅在 Swift 中随机播放结构的一部分
【发布时间】:2020-10-03 18:09:53
【问题描述】:

我有一个留言板,其中的项目在从数据库中检索时按最新到最旧排序。但是,在按时间顺序加载结构后,我希望第一项是当前用户的消息,无论它是否是最新的。我尝试使用下面的函数来执行此操作,但结果是按顺序对用户名进行排序。

结构代码

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 }

【问题讨论】:

  • 如何知道一条消息是否是“当前用户的消息”?
  • @Sweeper,我添加了结构代码。我知道消息是否是当前用户的,因为用户名是存储在结构中的值之一。

标签: ios arrays swift sorting struct


【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2023-01-23
    • 2017-09-22
    相关资源
    最近更新 更多