类属性返回nil

时间:2018-06-21 14:37:07

标签: swift class firebase firebase-realtime-database properties

我正在与FirebaseDatabase合作来存储数据。我有一个简单的模型,可将snapshot数据转换为post。问题在于,在观察了snapshot之后,名为postType的属性返回了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

1 个答案:

答案 0 :(得分:2)

Post.typeenum,不能仅仅将其设置为String。您所拥有的等同于: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)

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