'My Tip Calculator doesn't work if I get these erors?
I'm new coding with Swift and I'm doing YouTube's beginner projects to learn, and currently I'm building a tip calculator, but I have the next errors:
Non-constant range: argument must be an integer literal
Instance member 'tipPercentages' cannot be used on type 'ContentView'; did you mean to use a value of this type instead?
And this is my code:
import SwiftUI
struct ContentView: View {
@State private var checkAmount = ""
@State private var numberPeople = ""
@State private var tipPercentage = 2
let tipPercentages = [10, 15, 20, 25, 0]
var totalPerPerson: Double {
let peopleCount = Double(numberPeople) ?? 0
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipVaule = (orderAmount / 100) * tipSelection
let grandTotal = orderAmount + tipVaule
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
var totalAmount: Double {
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipValue = (orderAmount / 100 ) * tipSelection
let grandTotal = orderAmount + tipValue
return grandTotal
}
var body: some View {
NavigationView {
Form{
Section{
TextField("Amount", text: $checkAmount)
.keyboardType(.decimalPad)
TextField("Number of people:", text: $numberPeople).keyboardType(.numberPad)
}
Section(header: Text("How much tip do you want to leave")) {
Picker("Tip Percentage", selection: $tipPercentage){
ForEach(0..<tipPercentages.count){
Text("\(Self.tipPercentages[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle(])
}
Section(header: Text("Amount per person")){
Text("$\(totalPerPerson, specifier: "$.2f")")
}
Section(header: Text ("Total amount of the check")){
Text("$\(totalAmount, specifier: "N.2f")")
.foregroundColor(tipPercentage == 4 ? .red : .primary)
}
.navigationBarTitle("SplitTip")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Solution 1:[1]
This is what i found at first glance. Your code is full of typos.
First use this constructor to itterate over the array:
ForEach(tipPercentages, id: \.self){ percentage in
Text("\(percentage)%")
}
and change this:
.pickerStyle(SegmentedPickerStyle())
edit:
The reason for the fatal error is because we changed the selection. Until now you saved the index of the array in tipPercentage
. Now you save the percentage itself. So you do not longer need to refer to the index.
Remove this:
let tipSelection = Double(tipPercentages[tipPercentage])
Change this:
let tipValue = orderAmount * tipPercentage / 100 //No need for brackets here :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |