如何在不使用可选值的情况下使用Firebase [英] How to work with Firebase without allowing optional values

查看:115
本文介绍了如何在不使用可选值的情况下使用Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS开发的新手,我了解在对象初始化时允许可选值并不是一项好公民"技术.话虽如此,我已经读到,始终设置值是一个好习惯,像这样:

I'm new to iOS development and I understand that allowing optional values when an object is initialized is not a 'good citizen' technique. That being said, I've read that it is good practice to always have values set, like this:

class Item{
    var name: String
    var color: String
    init(name: String, color: String) {
        self.name = name
        self.color = color
    }
}

这看起来很整洁,但是如何使用Firebase进行类似的操作?看看我到目前为止有什么:

This looks nice and tidy but how can I do something like that working with Firebase? Look what I've got so far:

private func loadPosts(){
    databaseHandle = ref.child("users/\(self.user.uid)/posts").observe(.value, with:{(snapshot) in
        var newPosts = [Post]()

        for itemSnapShot in snapshot.children {
            let post = Post(snapshot: itemSnapShot as! FIRDataSnapshot)
            newPosts.append(post!)
        }
        self.posts = newPosts
        self.tableView.reloadData()
    })
}

这个人被放置在我的PostsViewController中,在那里我可以看到表格视图.这是我的模型:

This guy is placed in my PostsViewController where I have my table view. This is my model:

class Post {
    var ref: FIRDatabaseReference?
    var title: String?
    var answer: String?
    var contentUrl: String?
    var photoUrl: String?
    var createdAt: String?
    var feeling: String?
    var kind: String?
    var text: String?
    var uid: String?
    var measurements: Dictionary<String, String>?

    //MARK: Initialization
    init?(snapshot: FIRDataSnapshot){
        ref = snapshot.ref

        let data = snapshot.value as! Dictionary<String, Any>

        title = data["title"]! as? String
        answer = data["answer"] as? String
        contentUrl = data["content_url"] as? String
        photoUrl = data["photo_url"] as? String
        createdAt = data["created_at"] as? String
        feeling = data["feeling"] as? String
        kind = data["kind"] as? String
        text = data["text"] as? String
        uid = data["uid"] as? String
        measurements = data["measurements"] as? Dictionary<String, String>
    }
}

我不知道为什么,但是那些问号感觉并不正确,然后我偶尔会得到零指针错误,我认为我应该可以通过使用好公民"技术来避免.

I don't know exactly why but those question marks doesn't feel quite right and now and then I get some nil pointer error, which I think I should be able to avoid by using the 'good citizen' technique.

那么,有人知道我该如何按照Swift的最佳做法来使用Firebase?

So, does anybody know how can I use Firebase following Swift best practices?

推荐答案

您是希望允许Post类的属性为nil还是不为您

Either you wish to allow the properties of your Post class to be nil or you don't.

如果您这样做,那很好.您发布的代码允许其中任何一个都不为零.您只需要在每次需要时都安全地访问每个属性.

If you do, that's fine. The code you posted allows any of them to be nil. You just need to safely access each property every time you need it.

如果不这样做,则不要使它们成为可选的.然后,在您的init中,如果快照中没有值,请为每个属性设置默认值,以确保没有将任何属性设置为nil.

If you don't, then don't make them optional. Then in your init you need to ensure none of the properties are set to nil by giving each a default if there is no value in the snapshot.

class Post {
    var ref: FIRDatabaseReference
    var title: String
    var answer: String
    var contentUrl: String
    var photoUrl: String
    var createdAt: String
    var feeling: String
    var kind: String
    var text: String
    var uid: String
    var measurements: [String : String]

    //MARK: Initialization
    init?(snapshot: FIRDataSnapshot) {
        if let data = snapshot.value as? [String : Any] {
            self.ref = snapshot.ref

            title = data["title"] as? String ?? ""
            answer = data["answer"] as? String ?? ""
            contentUrl = data["content_url"] as? String ?? ""
            photoUrl = data["photo_url"] as? String ?? ""
            createdAt = data["created_at"] as? String ?? ""
            feeling = data["feeling"] as? String ?? ""
            kind = data["kind"] as? String ?? ""
            text = data["text"] as? String ?? ""
            uid = data["uid"] as? String ?? ""
            measurements = data["measurements"] as? [String : String] ?? [:]
        } else {
            return nil
        }
    }
}

请注意这如何确保有适当的快照.请注意,如果快照中没有值,则如何为每个属性设置默认值.显然,您可以分配所需的任何默认值.我以空字符串为例.

Note how this ensures there is a proper snapshot. Note how a default value is set to each property if there is no value in the snapshot. Obviously you can assign any default you wish. I use the empty string as an example.

即使您希望将属性设置为nil,也应至少更新代码以检查是否有有效的快照,如上面的代码一样.

Even if you want to allow the properties to be nil, you should at least update your code to check for a valid snapshot like in the code above.

当然,您可以组合使用某些属性不能为nil且某些属性可以为.这取决于您的需求.

Of course you can have a combination where some properties can't be nil and some can. That's up to your needs.

这篇关于如何在不使用可选值的情况下使用Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆