You might receive two types of answers. Since this is a learning site, I'll try to provide you with a few hints that you can think about and try coding on your own.
Functions vs Computed Properties
Your calculateBedtime() function probably looks like this:
func calculateBedTime() {
do {
// === Wire up machine learning model =======================
let config = MLModelConfiguration()
let model = try SleepCalculator(configuration: config)
// === Extract components from a date and time Calendar object =============
let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
let hour = (components.hour ?? 0) * 60 * 60
let minute = (components.minute ?? 0) * 60
// === Perform a calculation ===========================
let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount)
let sleepTime = wakeUp - prediction.actualSleep
recommendedBedTime = sleepTime
// === Display a response =====================
alertTitle = "Your ideal bedtime is…"
alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
} catch {
// === Display an error message ==================
alertTitle = "Error"
alertMessage = "Sorry, there was a problem calculating your bedtime."
} // end of do-catch
showingAlert = true
} // end of function
Because this is a function
, you need a way to tell SwiftUI to execute it. Of course, the standard way might be to call this function by tapping a Button()
.
But what might you do to compute (<-- hint!) the bedtime value whenever any of the input variables change? You might want to review the lessons on computed variables!
// Function vs Computed Variable example
// Goal: Compute the area of a rectangle
var rectangleSideLength = 5.0
var rectangleBaseLength = 10.0
// You need a button to execute this function and calculate the area
func rectangleArea() -> Double {
return rectangleSideLength * rectangleBaseLength // <-- Maths
}
// This declares a variable. But the value isn't stored...it's calculated.
// Whenever the length or the base change values,
// the rectangleArea is automatically, and immediately calculated!
// If this variable is used in a view, the view redraws itself immediately.
var rectangleArea: Double {
return rectangleSideLength * rectangleBaseLength // <-- immediate calculation
}
Keep coding!
Hope this pushes you in the right direction!