字典转换为自定义类

字典转换为自定义类

我正在尝试将此字典转换为自定义类,但在let comment = aComment as! messageComments处获取了SIGABRT,如何将字典转换为自定义类messageComments

["comment1": {
    color = grape;
    content = "a comment ";
    date = 563954564;
    "icon " = referee;
    userName = "anotherUser ";
}, "comment2": {
    color = grape;
    content = "another comment ";
    date = 563954564;
    icon = referee;
    userName = "user";
}]



let comments = messages.childSnapshot(forPath: "comments").value as?[String: Any] ?? [:]

            for aComment in comments.values {
                let comment = aComment as! messageComments
                let theComment = messageComments(content: comment.content, color: comment.color, icon: comment.icon, date: comment.date, userName: comment.userName)
                commentArray.append(theComment)
            }

最佳答案

这是解决方案

let comments = messages.childSnapshot(forPath: "comments").value as? [String: Any] ?? [:]



                for comment in comments {

                    let theComment = comment.value as? [String: Any]

                    let theContent = theComment?["content"] as? String ?? ""
                    let theIcon = theComment?["icon"] as? String ?? ""
                    let theColor = theComment?["color"] as? String ?? ""
                    let theDate = theComment?["date"] as? String ?? ""
                    let theName = theComment?["userName"] as? String ?? ""

                    let aComment = messageComments(content: theContent, color: theColor, icon: theIcon, date: theDate, userName: theName)
                    commentArray.append(aComment)

                }

关于swift - 如何在Swift中将字典转换为自定义类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53387803/

10-14 00:51