Reputation: 89
My result is the simulator freezing.
My expected result is for the program to add random numbers until a 7 comes up when I press the "Not Seven" button.
My goal is to complete this challenge: *Build a UI with a List and three Buttons below it.
When the first button is tapped:
Add a random integer (from 1 to 10) to the List. If the integer you added to the List wasn't a 7, then keep adding random integers (from 1 to 10) to the List until you add a 7 to the List. When the second button is tapped:
Increase all the integers shown in the List by 1 When the third button is tapped:
Clear all the numbers from the List.
This is a link to a recording of the program: https://files.fm/f/t5trf3ww3
import SwiftUI
struct ContentView: View {
@State var numbers = [Int]()
var body: some View {
VStack {
List(numbers, id: \.self) { num in
Text(String(num))
}
HStack {
Button("Not Seven") {
var randNumber = 0
randNumber = Int.random(in: 0...10)
repeat{
numbers.append(randNumber)
}while randNumber != 7
}
Button("Add 1 to All") {
for index in 0...numbers.count - 1 {
numbers[index] += 1
}
}
Button("Delete") {
numbers.removeAll()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
ContentView()
}
}
}
Upvotes: 0
Views: 171
Reputation: 9675
You are never actually changing randNumber
in your loop.
Button("Not Seven") {
// You initialize the variable
var randNumber = 0
// You set it to a random Int
randNumber = Int.random(in: 0...10)
//Then you test forever if that random Int is 7. You have a 1 in 11 chance of an infinite loop, which is why the simulator hangs.
repeat{
numbers.append(randNumber)
}while randNumber != 7
}
Change button to:
Button("Not Seven") {
// No need to set it to 0 and then change it to a random Int prior to the loop.
var randNumber = Int.random(in: 0...10)
repeat {
numbers.append(randNumber)
//Change randNumber here to be a different random number.
randNumber = Int.random(in: 0...10)
} while randNumber != 7
}
You could probably rework the logic to not have two different `randNumber = Int.random(in: 0...10)' statements, but I have finished my coffee yet to think about that.
Upvotes: 1