【问题标题】:How to make non optional String Optional in Swift如何在 Swift 中使非可选字符串可选
【发布时间】:2020-12-10 11:05:03
【问题描述】:

我在我的应用程序中实现了 Stripe,所以当我在 swift 中将我的 customer_id 作为参数发送时,它必须是可选的,否则它不起作用。但是我从 firebase 中提取 id 作为非可选值。有什么方法可以将非可选 id 转换为可选变量。从 Firestore 获取 id 的代码:

docRef.getDocument(source: .cache) { (document, error) in
                                  if let document = document {
                                    id = document.get("id") as? String ?? ""
                                  } 

id 作为非可选返回。我需要发送一个可选变量作为 id(这是它的唯一工作方式):

var data = ["api_version" : apiVersion, "customer_id" : id]
        
        functions.httpsCallable("getStripeEphemeralKeys").call(data)

上面的代码给了我错误,但如果我发送与可选变量相同的确切 ID,它就可以工作

【问题讨论】:

  • 任何非可选的都可以分配给它们的可选对应类型,而不会产生任何编译器投诉。它到底在哪里不适合你?
  • customer_id 似乎是您的 firebase 函数参数,它是一个可选参数。也可能您可以定义您的文档,以便将 customer_id 存储为 customer_id 而不是实际的 document id,以便它可以是可选的
  • 你可以做 Optional.some(id) 但我怀疑这是你的问题
  • 您应该首先解释为什么将id 设为非可选。因为看起来只需将其声明为var id: String? 即可解决您的问题。然后将id = document.get("id") as? String 分配给它,没有?? "" 部分。

标签: swift google-cloud-firestore google-cloud-functions stripe-payments optional


【解决方案1】:

我解决了这个问题。如果您执行 document["id"} 而不是 document.get("id"),那么 firebase 如何返回 optional 真的很奇怪。

 var id:Any? = ""
        let docRef = db.collection("Profile").document((user?.email)!)
                              docRef.getDocument(source: .cache) { (document, error) in
                                  if let document = document {
                                    id = document["id"]
                                   var data = ["api_version" : apiVersion, "customer_id" : id]
                                    self.functions.httpsCallable("getStripeEphemeralKeys").call(data) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多