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

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.