如何在Swift中的Firebase中写入nil值?

时间:2017-12-15 01:12:37

标签: swift firebase

我有struct持有不同类型的数据,我想将其写入Firebase。我的结构的一些属性可以是nil,因此它们应该写在数据库中。

写入Firebase时如何处理nil值?

 struct Booking{

  let bookingNumber:String
  let bookingCompleted:Bool
  let cancelledBy:[String:AnyObject]?

       init(bookingNumber:String,
          bookingCompleted:String){
         self.bookingNumber = bookingNumber
         self.bookingCompleted = bookingCompleted
        }

      init(cancelledBy:[String:AnyObject]){
           self.cancelledBy = cancelledBy
        }
}

class DisbursePayment {

   override func viewDidLoad() {
    super.viewDidLoad()
   //how to handle if cancelledBy is nil? It will throw error :  unexpectedly 
   //found nil while unwrapping an Optional value
   //How should I structure my data in `struct Booking`?
   let item = Booking(cancelledBy: valueCouldBeNil)  
  }
}

1 个答案:

答案 0 :(得分:1)

从评论中看来,您似乎已经找到了解决方案,我想为其他人添加以下信息作为参考:

如果不需要值,则不应将nil值存储在firebase(或任何数据库中,因为它会因重复值而中断1NF),只应将其设置为数据库(如果存在)。否则将其初始化为nil并使用Optional Chaining安全地展开值(如果存在)。

考虑以下对象将其非必需属性'title'初始化为nil

   //Create a new reference to Firebase Database
   var ref: DatabaseReference!
   ref = Database.database().reference().child(<#your child id#>)

    //Make a Dictionary of values to set
    var values:[String:Any] = [:]

    //Set required values like uuid or other primary key

    //Use Optional Chaining to set the value
    //Note that if title is nil 
    //it doesn’t override any existing value in firebase for title i.e. the old value will still remain.
    if let title = myObject.title {
            values["title"] = title
          } else {
            //if the value was previously set but now is not, 
            //we should update firebase by removing the value.
            ref.child("title").removeValue()
         }

    //…

    //Finally, push the remaining values to firebase to up date the child
    ref.updateChildValues(values)

<强>设置

在firebase中设置值时,我们可以使用可选链接来设置值(如果存在),否则,不要将其添加到要保存到firebase中子对象引用的值中,并删除当前值(如果存在)。

    //Create a new reference to Firebase Database
    var ref: DatabaseReference!
    ref = Database.database().reference().child(<# child path #>)
    ref.queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot) in
            if (snapshot.value is NSNull) {
                print("No Items to Fetch")
            } else  {
                //enumerate over the Objects
                for child in snapshot.children.allObjects as! [DataSnapshot] {
                    if let object = child.value as? [String : AnyObject] {

                           let myObject = CustomObject()

                            if let title = object["title"] as? String {
                                   myObject.title = title
                              }
                               //If There is no value for 'title' it will not be set.
                               //…


//Then use the value as you normally would…
if (myObject.title != nil) {//..}

<强>获取

要从firebase获取值,我们再次使用Optional Chaining查看给定键的值是否存在,这里我通过子路径访问对象,您的查询可能不同但概念是相同的。< / p>

    $(document).ready(function() {
      $("button").click(function() {
      var ele =  $("td");
       $.each(ele,
            function() {
              alert($(this).text());
            }
          );
      });
    });