如何遍历Any的数组

时间:2018-12-28 21:45:47

标签: swift iteration

我想知道我将如何遍历一系列不同类型的对象。数组如下所示:

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 都是结构,如果有必要查看更多代码,请询问。

1 个答案:

答案 0 :(得分:4)

使用可选绑定:

navigationBar

guard let received = i as? ReceivedMessage messages采用通用协议,而不是将[Any]声明为ReceivedMessage,然后SentMessage将是采用该协议的对象数组:

messages