0

I'm working on a project that involves a chat system

I would like to insert chatMessages to an array in the correct place (by id ) and get the index of it.

How could I achieve that?


One thing to mention, the message ids are normally Integers, but if you send a message then temporarily it gets a pendingId (for example "aBe3BwqKBe"), and the id gets the same value.

After the message is successfully sent, It receives the correct id from the database, and sets it correctly.


So for example I have an array with those messages:

id: "1"
id: "2"
id: "aBre4Jvwrk" (pending)
id: "5"
id: "6"

If I receive a message with id 4, I would like to insert it before the id 5, and I would like to get the index of it. How could I achieve that in such a complex situation?

Code:

class ChatRoom: NSObject {
    var id : String!
    var pendingId : String?
    var title : String!
    var messages : [ChatMessage]
    var users : [Int]

    init(id : String, title: String, messages: [ChatMessage], users: [Int]){
        self.id = id
        self.title = title
        self.messages = messages
        self.users = users

        super.init()
    }

    func insertMessageAtCorrectPlace(message : ChatMessage) -> Int {
        // Insert message 
        messages.append(message)
    }
}

class ChatMessage: NSObject {
    var id : String!
    var pendingId : String?
    var userId: Int!
    var message: String!
    var sentTime: Int!

    init(id : String, userId: Int, message: String, sentTime : Int){
        self.id = id
        self.userId = userId
        self.message = message
        self.sentTime = sentTime

        super.init()
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kárpáti András
  • 1,221
  • 1
  • 16
  • 35
  • When sorting the array, how will you decide that `aBre4Jvwrk` goes after `2` and before `5`? – mag_zbc May 29 '19 at 12:10
  • 1
    *the message ids are normally Integers*. No, they aren't. The code clearly reveals that the ids are `String`. And please **never ever** declare properties as implicit unwrapped optional if they are initialized non-optional. Remove all exclamation marks – vadian May 29 '19 at 12:13

0 Answers0