1

I am working through hackingwithswift doing the 100 Days of SwiftUI and currently on Day 35 which needs me to build a times table app.

Unfortunately, I have got stuck at a very early stage and feel stupid asking.

How can I make my array index start at 1 rather than 0?

Below is my code and screenshot of the canvas:

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) = ") } } } 

SwiftUI Canvas

2
  • Could you please tell us a little bit more about the use case this is needed? What is your goal. Why does the array need to start at 1? Commented May 31, 2020 at 16:06
  • I was thinking having an array for the user to pick the multiplication table they wanted to play Thought this would be a good way of achinging that Commented May 31, 2020 at 16:11

1 Answer 1

2

From Apple documentation:

The first element of a nonempty array is always at index zero.

Basically you'd need to add +1 to your number variable.

var correctNumber: Int { number + 1 } 

And use this correctNumber when displaying values or performing calculations.

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

As correctNumber is a computed property it will always be up to date with number variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this has worked. Knew it was going to be stupidly obvious

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.