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

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?

   

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?

1      

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!

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building in-app subscriptions are hard. RevenueCat makes it simple. With their open source SDKs, you can painlessly implement subscriptions for your app in hours, not months.

Explore the docs to learn 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.

Snapthread is a casual video editor and slideshow maker that makes discovering, compiling and sharing your favorite memories effortless.

 
Unknown user

Not logged in

Log in