I am working on 100 days of swiftUI on hackingwithswift.com and I cannot get some code to work. I am on day 28 project 4 and I keep getting the error in the title when I try to add a picker to a section of my form. What am I doing wrong?
// ContentView.swift
// BetterRest
//
import CoreML
import SwiftUI
struct ContentView: View
{
@State private var wakeUp = defaultWakeTime
@State private var sleepAmount = 8.0
@State private var coffeeAmount = 1
@State private var alertTitle = ""
@State private var alertMessage = ""
@State private var showingAlert = false
static var defaultWakeTime: Date
{
var components = DateComponents()
components.hour = 7
components.minute = 0
return Calendar.current.date(from: components) ?? Date.now
}
var body: some View
{
NavigationView
{
Form
{
Section
{
Text("When do you want to wake up")
.font(.headline)
DatePicker("Please enter a time", selection: $wakeUp, displayedComponents: .hourAndMinute)
.labelsHidden()
}
Section
{
Text("Desired amout of sleep")
.font(.headline)
Stepper("\(sleepAmount.formatted()) hours", value: $sleepAmount, in: 4...12, step: 0.25)
}
Section
{
Picker("Daily coffee intake", selection: $coffeeAmount)
.font(.headline)
{
ForEach(1..<21)
{
Text($0 == 1 ? "1 cup" : "\($0) cups")
}
}
}
}
.navigationTitle("BetterRest")
.toolbar
{
Button("Calculate", action: calculateBedtime)
}
.alert(alertTitle, isPresented: $showingAlert) {
Button("OK") { }
} message: {
Text(alertMessage)
}
}
}
func calculateBedtime()
{
do
{
let config = MLModelConfiguration()
let model = try SleepCalculator(configuration: config)
let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
let hour = (components.hour ?? 0) * 60 * 60
let minute = (components.minute ?? 0) * 60
let prediction = try model.prediction(wake: Int64(hour + minute), estimatedSleep: sleepAmount, coffee: Int64(coffeeAmount))
let sleepTime = wakeUp - prediction.actualSleep
alertTitle = "Your ideal bedtime is..."
alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
} catch {
alertTitle = "Error"
alertMessage = "Sorry, there was a problem calculating your bedtime."
}
showingAlert = true
}
}
struct ContentView_Previews: PreviewProvider
{
static var previews: some View
{
ContentView()
}
}
The problem code is here:
{
Picker("Daily coffee intake", selection: $coffeeAmount)
.font(.headline)
{
ForEach(1..<21)
{
Text($0 == 1 ? "1 cup" : "\($0) cups")
}
}
}