有没有办法从子数组中读取?

Is there a way of reading from sub arrays?

我目前正在构建一个 iOS 应用程序,它使用 Google Firestore 存储用户添加的产品。添加的每个产品都连接到一个用户特定的“产品”数组中(如下所示 - 尽管有单独的数字,但它们是同一数组的一部分,但在 UI 中由 Google 分隔以显示每个单独的子阵列更清楚)

我使用以下语法 return 来自数据库中“产品”字段的第一个子数组的数据

  let group_array = document["product"] as? [String] ?? [""]
     if  (group_array.count) == 1 {
            
         let productName1 = group_array.first ?? "No data to display :("`
                        
         self.tableViewData =
                           [cellData(opened: false, title: "Item 1", sectionData: [productName1])]

                            }

return按以下格式编辑:

Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17

但是我正在尝试查询此子数组的每个单独部分,例如,我可以 return“产品名称:1”而不是整个子数组。由于 let productName1 = group_array.first 用于 return 第一个子数组,我尝试 let productName1 = group_array.first[0] 尝试 return 这个子数组中的第一个值但是我收到以下错误:

Cannot infer contextual base in reference to member 'first'

所以我的问题是,参考我的数据库中的图像(在我的问题的顶部),如果我只想 return 来自示例子数组的“产品名称:1”,是这是可能的,如果是的话,我将如何提取它?

我会重新考虑将产品存储为需要解析的长字符串,因为我怀疑有更高效、更不容易出错的模式。但是,这种模式是 JSON 的工作方式,所以如果您希望以这种方式组织产品数据,那么让我们用它来解决您的问题。

let productRaw = "Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17"

您可以做的第一件事是将字符串解析为组件数组:

let componentsRaw = productRaw.components(separatedBy: ", ")

结果:

["Product Name: 1", "Listing Price: 3", "A brief description: 4", "Product URL: 2", "Listing active until: 21/04/2021 10:22:17"]

然后您可以使用子字符串搜索此数组,但为了提高效率,让我们将其翻译成字典以便于访问:

var product = [String: String]()

for component in componentsRaw {
    let keyVal = component.components(separatedBy: ": ")

    product[keyVal[0]] = keyVal[1]
}

结果:

["Listing active until": "21/04/2021 10:22:17", "A brief description": "4", "Product Name": "1", "Product URL": "2", "Listing Price": "3"]

然后简单地通过它的键找到产品:

if let productName = product["Product Name"] {
    print(productName)
} else {
    print("not found")
}

这里有很多注意事项。产品字符串必须始终统一,因为逗号和冒号必须始终遵循这种严格的格式。如果产品名称有冒号和逗号,这将不起作用。您可以修改它来处理这些情况,但它可能很快变成一碗意大利面条,这也是我建议完全使用不同数据模式的原因。您还可以探索将数组转换为字典的其他方法,例如使用 reducegrouping,但存在大 O 性能警告。但如果这是你想要走的路,这将是一个很好的起点。

综上所述,如果您真的想使用此数据模式,请考虑在产品字符串中添加分隔符。例如,自定义分隔符将大大减少处理边缘情况的需要:

let productRaw = "Product Name: 1**Listing Price: 3**A brief description: 4**Product URL: 2**Listing active until: 21/04/2021 10:22:17"

使用像 ** 这样的分隔符,值可以包含逗号而无需担心。但为了完全安全(和效率),我会添加第二个分隔符,以便值可以包含逗号或冒号:

let productRaw = "name$**price$**description$**url$**expy$/04/2021 10:22:17"

有了这个字符串,您可以通过 ** 更安全地解析组件,通过 $$ 解析键的值。它看起来像这样:

let productRaw = "name$**price$**description$**url$**expy$/04/2021 10:22:17"
let componentsRaw = productRaw.components(separatedBy: "**")
var product = [String: String]()

for component in componentsRaw {
    let keyVal = component.components(separatedBy: "$$")
    product[keyVal[0]] = keyVal[1]
}

if let productName = product["name"] {
    print(productName)
} else {
    print("not found")
}