Wayne Rumble Wayne Rumble - 2 months ago 10
Swift Question

Display two arrays of custom objects in order of date received

i have two arrays of custom objects([InboundMessages],[OutboundMessages])

struct InboundMessage {

let senderName: String!
let senderText: String!
let senderProfileImageName: String!
let timeAndDateMessageReceived: NSDate!
let hasBeenRead: Bool!
let messageUUID = NSUUID().UUIDString
let conversationUUID: NSUUID = NSUUID()

}
struct OutboundMessage {

var replyText: String!
var messageUUID = NSUUID().UUIDString
var timeAndDateMessageSent: NSDate!
var conversationUUID: NSUUID = NSUUID()
}


that are held with another custom object 'Conversation'

class Conversation {

var uUID: NSUUID!
var inboundMessages: [InboundMessage] = []
var outboundMessages:[OutboundMessage] = []

}


I'd like to display the conversation ordered by date within a tableview like a normal conversation would be but i cant get my head around how to do it after many attempts. I feel like it would be best to push them all into a sorted array and then let the tableview deal with it but im still not sure how to sort them and then how to put two different custom objects into the same array?

You may have guessed that im very new to swift and iOS so any help would be much appreciated.

Thanks

Answer

1. Create an base class:

class Message {
    let timeAndDateMessageReceived: NSDate!
    let hasBeenRead: Bool!
    let messageUUID = NSUUID().UUIDString
    let conversationUUID: NSUUID = NSUUID()
}

2. Extend Message class:

class OutboundMessage: Message
class InboundMessage: Message

3. Create a Message array:

var messages: [Message] = inboundMessages.map() {
return $0 as Message
} + outboundMessages.map() {
    return $0 as Message
}

4. Order it by timeAndDateMessageReceived:

messages.sort({ $0.timeAndDateMessageReceived.compare($1. timeAndDateMessageReceived) == NSComparisonResult.OrderedAscending })
Comments