ios - 线程 1 : Fatal error: NSArray element failed to match the Swift Array Element type

标签 ios swift

我的消息自定义类是这样声明的:

class Message: SBDBaseMessage {

    var text : String?
    var date: Date?

    init(text: String, date: Date) {
        super.init()
        self.text = text
        self.date = date
    }
}

注意:SBDBaseMessageSendBird 消息框架的自定义消息类型。

然后,我有一个像这样声明的空数组:

var messages: [Message] = [Message]()

在下面的代码块中,我收到了这条崩溃消息(在第二行)->

Thread 1: Fatal error: NSArray element failed to match the Swift Array Element type

代码如下:

func sendMessage() {
    if let channel = self.groupChannel {
        channel.sendUserMessage(textView.text) { (message, error) in
            guard error == nil else { return }
            let newMessage: Message = Message(text: (message?.message)!, date: Date())
            self.messages.append(newMessage)
            self.tableView.reloadData()
        }
    }
}

此处的消息是 SBDUserMessage,它继承自 SBDBaseMessage

我做错了什么?任何帮助将不胜感激

最佳答案

好的,我找到了这个错误的原因。 我的 messages 数组被附加到另一个带有 SBDUserMessages 的代码块中,我没有将它们转换为确切的消息类型(as!SBDUserMessage).

调试确实帮了大忙。在某些时候,我决定在 self.messages.append(newMessage)(崩溃实际发生的地方)之前调用 messaged.removeAll(),之后我发现一切正常很好。

关于ios - 线程 1 : Fatal error: NSArray element failed to match the Swift Array Element type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721235/

相关文章:

ios - 在 UITableViewCell 中设置数据

ios - NSKeyedUnarchiver decodeObjectForKey :]: cannot decode object of class

ios - 如何在 iPad 上将 AdMob 广告居中?

swift - 如何访问 ARSCNDebugOptions.showBoundingBoxes?

swift - 在没有 socket 的情况下以快速方式以编程方式创建 ScrollView

ios - swift 3 - 推送通知的本地化不起作用

ios - 获取接入点列表及其信号强度

ios - 应用程序运行时播放音频

ios - Swift FMDB 代码说明

ios - 向 GMSPlacePicker(iOS) 添加搜索栏