首页 > 解决方案 > 类属性返回 nil

问题描述

我正在使用FirebaseDatabase存储数据。我有一个简单的模型,可以将snapshot数据转换为post. 问题是,在观察 后snapshot,名为postTypereturn的属性nil我不知道为什么。

class Post {

    var id           : String?
    var title        : String?
    var content      : String?
    var source       : String?
    var userUid      : String?
    var type         : PostType?
}

extension Post {

    static func transformDataToImagePost (dictionary: [String : Any], key: String) -> Post {
        let post = Post()
        post.id        = key
        post.userUid   = dictionary["userUid"] as? String
        post.title     = dictionary["title"] as? String
        post.content   = dictionary["content"] as? String
        post.source    = dictionary["source"] as? String
        post.type = dictionary["postType"] as? PostType

        return post
    }


enum PostType: String {

    case image = "image"
    case gif = "gif"
    case video = "video"
    case text = "text"
    case link = "link"
    case audio = "audio"
    case poll = "poll"
    case chat = "chat"
    case quote = "quote"
}


func observePost(withId id: String, completion: @escaping (Post) -> Void) {
    REF_POSTS.child(id).observeSingleEvent(of: .value, with: {
        snapshot in
        if let dictionary = snapshot.value as? [String : Any] {
            print(snapshot.value) // <- ["key":value, "postType": text, "key": value]
            print(dictionary["postType"]) // <- returns text
            let post = Post.transformDataToImagePost(dictionary: dictionary, key: snapshot.key)
            print(post.type)  // <- returns nil
            completion(post)
        }
    })
}

我就是想不通为什么post.type退货nil

标签: swiftclassfirebasefirebase-realtime-databaseproperties

解决方案


Post.type是一个enum,你不能只将它设置为一个字符串。你所拥有的相当于:post.type = "text"

尝试以这种方式初始化它:

post.type = PostType(rawValue: dictionary["postType"])

您可能需要先解开该值。

if let postType = dictionary["postType"] as? String {
     post.type = PostType(rawValue: postType)
}

如何在操场上像这样初始化枚举的示例:

enum PostType: String {

    case image = "image"
    case gif = "gif"
    case video = "video"
    case text = "text"
    case link = "link"
    case audio = "audio"
    case poll = "poll"
    case chat = "chat"
    case quote = "quote"
}

let postType = PostType(rawValue: "poll")
print(postType)

输出可选(__lldb_expr_339.PostType.poll)

您可以在文档中阅读有关枚举的更多信息。对于这个特定的问题;查找标题:“从原始值初始化”


推荐阅读