-1

I want to know how I would iterate over an array of objects of different types. The array looks like this:

var messages: [Any] = [SentMessage(sent_text: "Halla", date_sent: "24.des", isSent: true, sending: false), RecievedMessage(profile_image: UIImage(named: "baseline_account_box_black_18pt")!, recieved_text: "Hei hva skjer?", date_recieved: "25.des", isRecieved: true)]

I tried to convert iterator like this:

for i in messages{

    guard let received = ReceivedMessage(i) else{
        return
    }


}

ReceivedMessages and SentMessages are both structs, if it is necessary to see more code, just ask.

Elias Knudsen
  • 315
  • 2
  • 9

1 Answers1

4

Use optional binding :

guard let received = i as? ReceivedMessage

Instead of declaring messages as [Any], make ReceivedMessage and SentMessage adopt a common protocol and then messages would be an array of objects adopting that protocol:

protocol Message {

}

struct SentMessage: Message {

}

struct ReceivedMessage: Message {

}

var messages: [Message]
ielyamani
  • 17,807
  • 10
  • 55
  • 90