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