【问题标题】:Why in firestore will a if let statement change the type of a document variable?为什么在 firestore 中 if let 语句会更改文档变量的类型?
【发布时间】:2017-12-05 22:57:53
【问题描述】:

我只是希望得到一个解释:下面发生了什么。 在第一个 if let 语句中,其中 document = document flatmap 不再是 DocumentSnapshot 的成员,而在第二个 if let 中,我显然能够在 if let 语句中调用文档上的 flatmap。我只是不太明白为什么会这样。

我检查了类型,它们都是 DocumentSnapshots,唯一的区别是一个是可选的。

谢谢。

 var docref:DocumentReference?
 docref = db.collection("users").document(uid)
 docref?.getDocument { (document, error) in

      if let document = document{

       //document.flatmap won't work
       //value of DocumentSnapshot has no member flatmap

      }         

      if let profile = document.flatMap({$0.data()})
      {

         self.model.currentLoggedInUser?.id = profile["id"] as! String

      }

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    if let document = document 解开之前的document,并将其绑定到一个新的常量document,这会在{ ... } 中隐藏之前的document

    如果document 之前有T? 类型,则新的阴影documentT 类型。

    类似于常规的变量阴影:

    let a = 1
    
    if true {
        let a = 2 //shadows the outer `a`
        print(a) // => 2
    }
    

    总而言之,这段代码的行为类似于:

    let document: Document? = MaybeReturnADocument()
    
    if document != nil { // Illustrative only, don't do this!
        let document: Document = document! // shadows the outer document of type `Document?`
        ...
    }
    

    【讨论】:

    • 谢谢@亚历山大。我只是做了一些阅读。在您的 if true 声明中只是为了确认将 print(a) print 1?我认为它会在当前范围内打印变量的值(即2)
    • @Mike 哎呀,它应该打印 2,那是一个错字!
    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多