【问题标题】:Set Index of Array (SwiftUI)设置数组索引(SwiftUI)
【发布时间】:2020-09-18 23:09:23
【问题描述】:

我正在通过 hackingwithswift 完成 SwiftUI 的 100 天,目前是第 35 天,这需要我构建一个时间表应用程序。

不幸的是,我在很早的阶段就被卡住了,觉得问起来很愚蠢。

如何让我的数组索引从 1 而不是 0 开始?

下面是我的代码和画布截图:

struct ContentView: View {
    @State private var number = 0
    @State private var question = Int.random(in: 0..<13)

    let numberRange = Array<Int>(1 ... 12)

    var body: some View {
        VStack {
            Picker("What times tables do you want to test your knowledge on?", selection: $number) {
                ForEach(0 ..< numberRange.count) {
                    Text("\(self.numberRange[$0])")
                }
            }
            .pickerStyle(SegmentedPickerStyle())

            Text("What is \(number) x \(question) = ")
        }
    }
}

【问题讨论】:

  • 你能告诉我们更多关于这个需要的用例吗?你的目标是什么。为什么数组需要从 1 开始?
  • 我在想有一个数组供用户选择他们想玩的乘法表 认为这将是一个很好的解决方法

标签: arrays swift indexing swiftui picker


【解决方案1】:

来自 Apple 文档:

非空数组的第一个元素总是索引为零。

基本上,您需要将 +1 添加到您的 number 变量中。

var correctNumber: Int {
    number + 1
}

并在显示值或执行计算时使用此correctNumber

Text("What is \(correctNumber) x \(question)?")

由于correctNumber 是一个计算属性,它始终与number 变量保持同步。

【讨论】:

  • 谢谢,这已经奏效了。知道这将是显而易见的
猜你喜欢
  • 2020-05-09
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 2021-12-29
相关资源
最近更新 更多