我想知道我将如何遍历一系列不同类型的对象。数组如下所示:
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)]
我试图像这样转换迭代器:
for i in messages{
guard let received = ReceivedMessage(i) else{
return
}
}
ReceivedMessages 和 SentMessages 都是结构,如果有必要查看更多代码,请询问。
答案 0 :(得分:4)
使用可选绑定:
navigationBar
让guard let received = i as? ReceivedMessage
和messages
采用通用协议,而不是将[Any]
声明为ReceivedMessage
,然后SentMessage
将是采用该协议的对象数组:
messages