27: BetterRest, part 2

그루두·2024년 5월 10일
0

100 days of SwiftUI

목록 보기
36/108

100 days of swiftui: 27
https://www.hackingwithswift.com/100/swiftui/27

UI


DatePicker, Stepper, toolbar로 필요한 입력을 받을 수 있도록 설정했다.

코드 파일
https://github.com/treesofgroo/Ios-BetterRest/commit/c06bd3f5c3bfdb0da56aa76291a41ee3e3f31692

createMl model 적용

    func calculateBedTime() {
        do {
            let config = MLModelConfiguration()
            let model = try SleepCalculator(configuration: config)

            let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUpTime)
            let hour = (components.hour ?? 0) * 60 * 60
            let minute = (components.minute ?? 0) * 60

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

            alertTitle = "Your ideal bedtime is..."
            alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)

        } catch {
            alertTitle = "Error"
            alertMessage = "Sorry, there was a problem calculating your bedtime."
        }
        showingAlert = true
    }

지난번에 csv 파일을 분석한 mlmodel의 값을 적용할 수 있도록 함수를 작성했다.

❕create Ml의 원리를 모르고, 이러한 코드는 이해보단 순간의 적용뿐이라서 아쉽다.

코드 파일
https://github.com/treesofgroo/Ios-BetterRest/commit/a77e3072262d04083b090a85ecddce2e71c32828

UI 수정

    @State private var wakeUpTime = defaultWakeTime
    // ... 
    static var defaultWakeTime: Date {
        var components = DateComponents()
        components.hour = 8
        components.minute = 0
        return Calendar.current.date(from: components) ?? .now
    }
    // ... 
                    VStack(alignment: .leading, spacing: 0) {
                    Text("Daily coffee intake")
                        .font(.headline)
                    Stepper("^[\(coffeeAmount) cup](inflect: true)", value: $coffeeAmount, in: 0...20)
                }
                // ...

전체 View를 Form으로 변경하고, DateComponents를 활용해 wakeUpTime의 default값을 설정하고, 특정 Markdown을 활용해 cup/cups를 나타냈다.

defaultWakeTime을 static으로 설정하면, ContentView struct의 instance가 아닌 ContentView 자체에 소속됨으로써 특정 속성의 존재에 의존하지 않는다. 그럼으로써 언제든 읽을 수 있다.

코드 파일
https://github.com/treesofgroo/Ios-BetterRest/commit/e1d61d81b4f4461ea1ade85c335f28ae93701535

profile
계속 해보자

0개의 댓글

관련 채용 정보