WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day 28 Picker can not change the View

Forums > 100 Days of SwiftUI

Hey guys.Today I try to change the betterRest but have shome problem. Here is my code. Anything helpful is very well.

when I changed Picker value there is no answer showed. But when I change the Stepper it will showed the answer.

//  ContentView.swift
//  Better Rest
//  Created by chen on 2022/1/27.

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 recommandWakeUpTime = ""
    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var showingAlert = false

    static var defaultWakeTime:Date{
        var conponents = DateComponents()
        conponents.hour = 7
        conponents.minute = 0
        return Calendar.current.date(from: conponents) ?? Date.now

    var body: some View {
                    Text("When do you want to wake Up?")

                    DatePicker("Please enter a time", selection: $wakeUP,displayedComponents: .hourAndMinute)
                    Stepper("Sleep \(sleepAmount.formatted()) hours", value: $sleepAmount,in: 4...12,step: 0.25){ _ in calculateBedTime()}

                    Text("Daily coffee intake")
                    Picker("How many Cup of Coffee you drink", selection: $coffeeAmount) {
                        ForEach(1..<21) {
                            Button("\($0)", action: calculateBedTime)
                    Text("Recommand wakeUp Time is")
            //    .navigationTitle("BetterRest")
//                .toolbar {
//                    Button("Calculator",action: calculateBedTime)
//                }
//                .alert(alertTitle, isPresented: $showingAlert) {
//                    Button("OK") { }
//                } message: {
//                    Text(alertMessage)
//                }
    func calculateBedTime(){
            let config = MLModelConfiguration()
            let model = try SleepCalculator(configuration: config)

            let componenets = Calendar.current.dateComponents([.hour, .minute], from: wakeUP)
            let hour = (componenets.hour ?? 0) * 60 * 60
            let minute = (componenets.minute ?? 0) * 60
            let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
            let sleepTime = wakeUP - prediction.actualSleep

            alertTitle = "Your ideal bedtime is…"
            alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
            recommandWakeUpTime = sleepTime.formatted(date: .omitted, time: .shortened)
            showingAlert = true
            alertTitle = "Error"
            alertMessage = "Sorry, there was a problem calculating your bedtime."
            showingAlert = true

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {


Try put a DatePicker with a default, like what you did with the wakeup time. Notice that you want the bedtime, not the wake-up time.

 @State private var idealBedTime = Date.now // this shows a default value of your idealBedTime.
                Section {
                    DatePicker("Please enter a time", selection: $idealBedTime, displayedComponents: .hourAndMinute).labelsHidden()
                } header: {
                    Text("Your ideal bedtime: ").font(.largeTitle)
let idealBedTime = sleepTime //do this in your function

Right now you don't see anything before you hit the Stepper because your calculateBedTime() function is not triggered until you hit the Stepper. Since there is no default value there, you don't see anything displayed because calculation has not been executed yet.


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.