UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 28 - Challenge - How do I trigger a function without a button?

Forums > SwiftUI

Dear Team,

I am unable to complete the last (third) challenge here. My primary confusion is:

How do I trigger a function without a button?

I tried to create a static computed property to have it triggered by @State, but a computed property requires a type annotation — which confuses me because the function doesnt return anything... What do I do? I'm considering rewatching everything from before Day 15... but I don't know if there is something obvious I am missing.

Please help me if you can.

Best, Ara.

import CoreML
import SwiftUI

struct ContentView: View {

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

    @State private var wakeUp = defaultWakeUpTime
    @State private var sleepAmount = 8.0
    @State private var coffeeCups = 1
    @State private var sleepTime = ""

    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var showingAlert = false

    var body: some View {
        NavigationStack {
            Form {

                Section("When do you want to wake up?") {
                    DatePicker("Please select a time:", selection: $wakeUp, displayedComponents: .hourAndMinute)
                        .labelsHidden()
                }

                Section("How long do you want to sleep?") {
                    Stepper("\(sleepAmount.formatted()) hours", value: $sleepAmount, in: 4...12, step: 0.25)
                }

                Section("How much coffee did you drink today?") {
                    Picker("Select your quantity", selection: $coffeeCups) {
                        ForEach(1..<20) {
                            Text("^[\($0) cup](inflect: true)")
                        }
                    }
                }

                Section("Your Ideal Bedtime") {
                    Text("help!")
                }
            }
            .navigationTitle("BetterRest 17")
            .toolbar {
                Button("Calculate", action: calculateBedtime)
            }
            .alert(alertTitle, isPresented: $showingAlert) {
                Button("OK") {}
            } message: {
                Text(alertMessage)
            }
        }
    }

     func calculateBedtime() {
        do {
            let myConfig = MLModelConfiguration()
            let modelOne = try SleepCalculator(configuration: myConfig)

            let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
            let wakeUpHour = (components.hour ?? 0) * 60 * 60
            let wakeUpMin = (components.minute ?? 0) * 60

            let predX = try modelOne.prediction(wake: Double(wakeUpHour+wakeUpMin), estimatedSleep: sleepAmount, coffee: Double(coffeeCups))
            let sleepTime = wakeUp - predX.actualSleep

            alertTitle = "Your ideal bedtime is..."
            alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)

        } catch {
            alertTitle = "Error."
            alertMessage = "Sorry! Something seems to have gone wrong while calculating your bedtime. Please try again."
        }
        showingAlert = true
    }
}

#Preview {
    ContentView()
}

2      

which confuses me because the function doesnt return anything

It seems that you have identified the only thing that is stopping you. Now, how can you fix that?

3      

Computed property is the right choice, but no need to make it static.

var calculateBedTime: String {
  // your do catch block goes here
}

and in your section you can simply adjust as follows:

Section("Your Ideal Bedtime") {
    Text("help!")

    Text("\(calculateBedTime)") // <- as soon as there changes in your calculation this text view will be updated and shows the time
}

3      

Triggering a function without a button can be a real game-changer, much like finding the perfect pickleball paddle. In the world of programming, there are various methods like using event listeners, timers, or even user interactions to execute functions without a direct button click. It's all about finding the right technique that suits your specific needs. Just like choosing the ideal pickleball paddle enhances your game, mastering these programming tricks elevates your coding skills. Happy coding, and here's to both seamless functions and winning shots on the pickleball court.

3      

Thank you all for your help. Here's the finished code — it works! But, does anyone have any pointers for improvement? Anything I can add or remove to it more efficient, maybe?

import CoreML
import SwiftUI

struct ContentView: View {

    @State private var sleepAmount = 8.0
    @State private var coffeeAmount = 2
    @State private var wakeUp = defaultWakeUpTime
    @State private var alertMessage = ""

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

    var calculateBedTime: String {
        do {
            let myConfig = MLModelConfiguration()
            let myModel = try MySleepCalculator(configuration: myConfig)

            let myDateComponents = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
            let hour = (myDateComponents.hour ?? 0) * 60 * 60
            let minute = (myDateComponents.minute ?? 0) * 60

            let myPrediction = try myModel.prediction(wake: Int64(hour + minute), estimatedSleep: sleepAmount, coffee: Int64(coffeeAmount))
            let sleepTime = wakeUp - myPrediction.actualSleep

            return sleepTime.formatted(date: .omitted, time: .shortened)

        } catch {
            alertMessage = "Something went wrong..."
        }
        return alertMessage
    }

    var body: some View {
        NavigationStack {
            Form {
                Section("When do you want to wake up?") {
                    HStack {
                        Spacer()
                        DatePicker("Wake up at:", selection: $wakeUp, displayedComponents: .hourAndMinute)

                    }
                }

                Section("How much sleep do you want?") {
                    Stepper("\(sleepAmount.formatted()) hours", value: $sleepAmount, in: 4...12, step: 0.25)
                }

                Section("How much coffee did you drink?") {
                    Picker("Coffee", selection: $coffeeAmount) {
                        ForEach(0..<21) {
                            Text("^[\($0) cup](inflect: true)")
                        }
                    }
                }

                Section("Your ideal bedtime is...") {
                    HStack {
                        Spacer()
                        Text(calculateBedTime)
                            .font(.largeTitle)
                        Spacer()
                    }
                }
            }
            .navigationTitle("My Sleep Calculator")
        }
    }
}
#Preview {
    ContentView()
}

Best, Ara.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

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.