swift - 类属性返回 nil

标签 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

最佳答案

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

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

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

您可能需要先解包该值。

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

如何在 playground 中像这样初始化枚举的示例:

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)

Output Optional(__lldb_expr_339.PostType.poll)

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

关于swift - 类属性返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971203/

相关文章:

java - 如何使用 Class 对象声明指定类型的 ArrayList

CSS - 无法获得一种跨度样式来覆盖另一种继承样式并左对齐

iOS Swift - 没有 Firebase 等模块

ios - CAShapeLayer strokeStart 和 strokeEnd 位置

Django 形成不刷新的类

ios - createCGImage(_ :from:) not using correct rect

ios - Firebase 临时封禁帐号

javascript - Firebase - 未捕获( promise )TypeError : Cannot read property

ios - 隐式成员表达式是用 Swift 编写的首选方式吗

ios - Swift 3 中的 AVAudioRecorder : Get Byte stream instead of saving to file