Предыдущие ответы верны, но, возможно, это поможет передать смысл.
Определить модель
struct ConversationViewModel {
private var chatMessages = [ChatMessage]()
func rowsInChat() -> Int{
return chatMessages.count
}
func messageFor(_ indexPath: IndexPath) -> ChatMessage{
return chatMessages[indexPath.row]
}
func setChat(_ chatMessages: [ChatMessages] {
var finalMessages = chatMessages.filter{ $0.senderId == viewer }
var notMyMessages = chatMessages.filter{ $0.senderId != viewer}.sorted(by: {$0.date < $1.date } )
var limit = notMyMessagescount > accountLimit ? accountLimit : notMyMessagescount
finalMessages.append( notMyMessages[0..<limit] ).sorted(by: {$0.date < $1.date } )
chatMessages = finalMessages
//should probably notify VC that data changed
}
}
struct ChatMessage {
let senderId : String
let message : String
let date : Date
}
заполнить модель
let messages = [
ChatMessage.init(senderId: "1", message: "hi", date: Date()),
ChatMessage.init(senderId: "2", message: "yo", date: Date().addingTimeInterval(1.0)),
ChatMessage.init(senderId: "1", message: "you code bro?", date: Date().addingTimeInterval(2.0)),
ChatMessage.init(senderId: "2", message: "fo sho", date: Date().addingTimeInterval(3.0)),
ChatMessage.init(senderId: "1", message: "let's get a beer", date: Date().addingTimeInterval(4.0)),
ChatMessage.init(senderId: "2", message: "nah", date: Date().addingTimeInterval(5.0)),
ChatMessage.init(senderId: "2", message: "you can't see this, its my 4th response", date: Date().addingTimeInterval(6.0)),
]
let model = ConversationViewModel()
model.setChat(messages)
и реализовать висточник данных табличного представления
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.rowsInChat()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = model.messageFor(indexPath)
if message.senderId == userID {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! CellTwo
cell.load(message)
return cell
}
else {
let cell =tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ConversationTableViewCell
cell.load(message)
return cell
}
}