【问题标题】:Do not create a document in firestore if string isEmpty如果字符串 isEmpty,请勿在 Firestore 中创建文档
【发布时间】:2018-07-16 22:08:43
【问题描述】:

我有从firstVC 传输到secondVC 的数据。 在firstVC 中,用户可以选择两个或一个字符串并将选定的字符串传输到secondVC。稍后在secondVC 中,用户可以将此字符串保存在 Firestore 中的文档中。

我的代码处理array of strings,但如果用户只选择一个字符串,我的代码必须只保存一个字符串。

如果第二个字符串为空,我怎么不能在 Firestore 中保存第二个字符串?

我的代码。

第二个VC:

var stringArray: [String] = []

@IBAction func confirmAndPaymentButtonTapped(_ sender: Any) {
     let bookingData: [String: Any] = ["name": name, "surname": surname]
     let bookingRef = Firestore.firestore().collection("Firestore")

     if stringArray[0].isEmpty {
         print("error in firstString")
     } else {
         bookingRef.document((confirmHallBooking?.id)!).
         collection("BookingDate").document(selectedDateTextField.text!).
         collection("BookingTime").document(stringArray[0]).setData(bookingData)
     }

     if stringArray[1].isEmpty {
         print("error in secondString")
     } else {
         bookingRef.document((confirmHallBooking?.id)!).
         collection("BookingDate").document(selectedDateTextField.text!).
         collection("BookingTime").document(stringArray[1]).setData(bookingData)
     }
}

现在,如果 stringArray[0]stringArray[1] 为空,我会收到错误消息,我不明白如何无法保存空字符串。

【问题讨论】:

  • 除了字符串为空时使用的打印语句之外,您还遇到什么错误?
  • @rmaddy Thread 1: Fatal error: Index out of range 在控制台中我看不到 print error in secondString
  • 指出导致该错误的确切代码行。
  • @rmaddy 在这条线上if secondString.isEmpty { 错误Thread 1: Fatal error: Index out of range
  • @rmaddy 我稍微更改了有问题的代码,请看。在这一行我得到一个错误if stringArray[1].isEmpty 错误Thread 1: Fatal error: Index out of range

标签: ios swift database google-cloud-firestore


【解决方案1】:

您的数组可能有 0、1 或 2 个字符串,这些字符串可能为空,也可能不为空。所以除了检查字符串是否为空之外,还需要检查数组中的字符串个数。

if stringArray.count > 0 {
    // There is at least 1 string in the array - check the first
    if !stringArray[0].isEmpty {
        bookingRef.document((confirmHallBooking?.id)!).
        collection("BookingDate").document(selectedDateTextField.text!).
        collection("BookingTime").document(stringArray[0]).setData(bookingData)
    }

    if stringArray.count > 1 {
        // There are at least 2 strings in the array - check the next one
        if !stringArray[1].isEmpty {
            bookingRef.document((confirmHallBooking?.id)!).
            collection("BookingDate").document(selectedDateTextField.text!).
            collection("BookingTime").document(stringArray[1]).setData(bookingData)
        }
    }
}

虽然上述方法有效,但如果您真的希望支持更多字符串,它很丑陋并且无法扩展。最好使用循环。

for string in stringArray {
    if !string.isEmpty {
        bookingRef.document((confirmHallBooking?.id)!).
        collection("BookingDate").document(selectedDateTextField.text!).
        collection("BookingTime").document(string).setData(bookingData)
    }
}

此循环将处理数组中的所有非空字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-09
    • 2019-02-16
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多