在 SwiftUI 中使用 ForEach 时计数错误

Wrong counting while using ForEach in SwiftUI

我在为我的项目搜索一些信息时发现了这个问题。它没有得到解答,但经过一些修复后我将其用作我的问题的答案'^^

问题:

how to change from default "2 cups" to 1 cup. ? My coffeAmmount is 1 so as I understand [=11=] should also be 1 in Text view. But its showing default as 2. Can someone explain ?

thanks.!!

代码:

import SwiftUI

struct ContentView: View {
     
@State private var coffeAmmount = 1
    
var body: some View {
     Section(header: Text("Daily coffe intake")
                        .font(.headline)){
                            Picker("How many cups", selection: $coffeAmmount){
                                ForEach(1..<21){
                                    Text([=10=] > 1 ? "\([=10=]) cups" : "\([=10=]) cup")
                                }
                            }
                    }
}
}

原题目: https://www.hackingwithswift.com/forums/100-days-of-swiftui/betterrest-day-28-challenge-2-how-to-create-a-simple-integer-picker/587

你只需要设置

coffeAmmount

到 0:

@State private var coffeAmmount = 0

SwiftUI 将此变量视为指向您使用 ForEach 创建的范围内位置的指针。 所以 ForEach 范围是 (1, 2, 3, ..., 20) 但它们的索引是 0 代表 1; 1 代表 2 等 Swift,许多编程语言默认从 0 而不是 1 开始计算索引和其他内容。

通过将 coffeAmmount 设置为 0,您实际上表明 Xcode 您想要索引中的值(放置在您创建的范围内)“品牌”0,其值为 1 :)

希望对遇到类似问题的人有所帮助,因为这个问题是 2 年前提出的。

另一个修复方法是将其设为数组,而不是范围。对于某些人来说,这可能更直观一些,因为您总是像这样处理 ForEach 中实际设置的数字:

struct CoffeeView: View {
    @State private var coffeAmmount = 1
    var body: some View {
        Picker("How many cups", selection: $coffeAmmount){
            // make this an Array and the value matches
            ForEach(Array(1..<21), id: \.self){ cup in
                Text(cup > 1 ? "\(cup) cups" : "\(cup) cup")
            }
        }
    }
}