简体   繁体   English

如何在正文视图中使用计数器来填充列表

[英]How do I use a counter within body View to fill a list

I am new to Swift and try to get a feeling for it by trying new things.我是 Swift 的新手,尝试通过尝试新事物来感受它。 Now I got stuck with lists.现在我被列表困住了。 I have two arrays, one is the product and the other the price for each product.我有两个arrays,一个是产品,另一个是每个产品的价格。 I want to fill a list by using a ForEach loop.我想使用 ForEach 循环来填充列表。 I use a HStack to have two columns.我使用 HStack 有两列。

To make it a bit more clear, here are the two arrays:为了更清楚一点,这里有两个 arrays:

@state private var products = ["Coke", "Fanta", "Sprite", "Water]
private var prices = ["1,43$", "1,22$", "1,64$", "0,45$"]

Now this is a part of my ContentView.swift:现在这是我的 ContentView.swift 的一部分:

var body: some View {
    List{
        ForEach(products, id: \.self) { product in
        HStack{
            Text(product)
            Spacer()
            Text(price[products.firstIndex(of: product)])
        }
    }
}

So my plan here is, to fill each cell with the product name by looping through the product array.所以我的计划是,通过遍历产品数组,用产品名称填充每个单元格。 Then I want to display the corresponding price.然后我要显示相应的价格。 For that I take my second Text and fill it with the price.为此,我使用我的第二个文本并用价格填充它。 To find the correct Index of the price array, I get the Index from my products array, since they are similar.为了找到价格数组的正确索引,我从我的产品数组中获取索引,因为它们是相似的。

That was my solution, but now I am getting an Error for the products.firstIndex(of: product) .那是我的解决方案,但现在我收到products.firstIndex(of: product)的错误。

I am getting following Error:我收到以下错误:

Value of optional type 'Array.Index?'可选类型“Array.Index?”的值? (aka 'Optional') must be unwrapped to a value of type 'Array.Index' (aka 'Int') (又名“可选”)必须展开为“Array.Index”类型的值(又名“Int”)

I am not really understanding what this Error is trying to tell me.我真的不明白这个错误试图告诉我什么。

Can anybody help?有人可以帮忙吗?

The correct code looks like this:正确的代码如下所示:

struct ContentView: View {

    private var products = ["Coke", "Fanta", "Sprite", "Water"]
    private var prices = ["1,43$", "1,22$", "1,64$", "0,45$"]

    var body: some View {
        List{
            ForEach(products, id: \.self) { product in
                HStack{
                    Text(product)
                    Spacer()
                    Text(self.prices[self.products.firstIndex(of: product)!])
                }
            }
        }
    }
}

The reason for your error is that the array could be empty at some point which leads to a crash if you try to read firstIndex in that moment.错误的原因是数组在某个时候可能为空,如果您在那一刻尝试读取 firstIndex 会导致崩溃。

Now you have two options:现在你有两个选择:

  1. Force-unwrap with an "."用“.”强制解包as I did above if you are sure the array will never be cleared/ be empty.就像我在上面所做的那样,如果您确定数组永远不会被清除/为空。
  2. Provide a default value with "?? value" if the value may be nil at some point.如果该值在某个时候可能为零,则使用“?? value”提供默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM