简体   繁体   中英

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. Now I got stuck with lists. I have two arrays, one is the product and the other the price for each product. I want to fill a list by using a ForEach loop. I use a HStack to have two columns.

To make it a bit more clear, here are the two 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:

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) .

I am getting following Error:

Value of optional type 'Array.Index?' (aka 'Optional') must be unwrapped to a value of type 'Array.Index' (aka '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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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