如何在Swift中将字典转换为自定义类型?

时间:2018-11-20 07:02:20

标签: swift dictionary

我正在尝试将此字典转换为自定义类,但是在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)
            }

1 个答案:

答案 0 :(得分:0)

这是解决方案

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)

                }