TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Day 28 - Challenge Three

Forums > 100 Days of SwiftUI

Hi,

I have met with some problems when trying to keep recomended bed time always on the screen. I didn't know how to call calculateBedTime function automatcially when any settings are changed if calculate button removed. I have tried onAppear but it seemed to only work on the first appearance.

Could someone help me on this?

2      

Hi @wctjerry,

it was a long time that I did this day so I had too look back what the challenge was 😛.

If I remember correctly the original project shown by Paul uses a button and when you press it, it will show the recommended bed time right?

Well if you want to automate this you just have to create a computed propterty with the name calculatedBedtime and the type String. A Computed property is always updated so you can just show that property inside a text block:

            Section(header: Text("Recommended Bedtime")) {
                Text("\(calculatedBedtime)")
                    .font(.largeTitle)
            }

The computed property I used is shown below but you might have to adjust it to your needs.

var calculatedBedtime: String {
    let model = SleepCalculator()

    let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
    let hour = (components.hour ?? 0) * 60 * 60
    let minute = (components.minute ?? 0) * 60
    var bedTime = "Please set all input values"

    do {
        let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
        let sleepTime = wakeUp - prediction.actualSleep

        let formatter = DateFormatter()
        formatter.timeStyle = .short
        bedTime = formatter.string(from: sleepTime)
    } catch {
        alertTitle = "Error"
        alertMessage = "Sorry, there was a problem calculating your bedtime."
        showingAlert = true
    }

    return bedTime
}

I hope this helps you further?

7      

A Computed property is always updated so you can just show that property inside a text block:

Thank you @@nicolinden , I didn't notice this way to use computed property. That works perfectly!

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.