https://github.com/seandev0601/100DaysOfSwiftUI
Day 26 - Project 4 - part 1 - 100DaysOfSwiftUI
Learning Time : 50 min
// Setting Up Properties
@State private var wakeUp = Date.now
@State private var sleepAmount = 8.0
@State private var coffeeAmount = 1
// Creating Date Picker for Wake Up Time
DatePicker("Please enter a time", selection: $wakeUp, displayedComponents: .hourAndMinute)
.labelsHidden()
// Implementing Stepper for Desired Sleep Amount
Stepper("\\(sleepAmount.formatted()) hours", value: $sleepAmount, in: 4...12, step: 0.25)
// Adding Stepper for Coffee Intake
Stepper(coffeeAmount == 1 ? "1 cup" : "\\(coffeeAmount) cups", value: $coffeeAmount, in: 1...20)
// Adding Button to Navigation Bar
.navigationTitle("BetterRest")
.toolbar {
Button("Calculate", action: calculateBedtime)
}
// Importing Core ML
import CoreML
do {
// Creating an Instance of the Core ML Model
let config = MLModelConfiguration()
let model = try SleepCalculator(configuration: config)
// Extracting Hour and Minute Components from Date
let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
let hour = (components.hour ?? 0) * 60 * 60
let minute = (components.minute ?? 0) * 60
// Making a Prediction using the Core ML Model
let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
// Calculating Bedtime and Displaying in Alert
let sleepTime = wakeUp - prediction.actualSleep
alertTitle = "Your ideal bedtime is…"
alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
} catch {
// Handle error
}
// Computed Property for Default Wake-Up Time
@State private var wakeUp = defaultWakeTime
static var defaultWakeTime: Date {
var components = DateComponents()
components.hour = 7
components.minute = 0
return Calendar.current.date(from: components) ?? Date()
}