Dekple
Dekple

Reputation: 67

Only shuffle part of a struct in Swift

I have a message board in which the items are sorted by newest to oldest when retrieved from the database. However, after loading the struct in the time order, I would like for the first item to be the current user's message regardless of if it's the latest one or not. I tried doing it with the function below but it turns out that sorts the usernames in order.

Struct Code

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]()

Sorting Code

self.messageBoardData.sort { (lhs, rhs) in return lhs.username > rhs.username }

Upvotes: 2

Views: 61

Answers (1)

Sweeper
Sweeper

Reputation: 271105

The closure you pass to sort is supposed to return true when lhs, rhs are in the desired order. Using this logic, we can write a modified version of the closure, that checks whether the username is the current user:

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

Upvotes: 1

Related Questions