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

Project 4 Better Rest Challenge #2

Forums > 100 Days of SwiftUI

Here is my code to change the textField to a picker. I get the error "Contextual closure type '() -> TupleView<(ForEach<Range<Int>, Int, _>, Text)>' expects 0 arguments, but 1 was used in closure body" and "Generic parameter 'Content' could not be inferred". Not sure what to do here

Text("Desired Amount of Sleep")
    .font(.headline)

Picker(selection: $sleepAmount,  label: Text("")){
    ForEach(1..<hours.count)
    Text(self.hours[$0])
                    }

3      

You need brackets for your ForEach:

Picker(selection: $sleepAmount,  label: Text("")){
    ForEach(1..<hours.count) {
        Text(self.hours[$0])
    }
}

3      

did that, and I get following error: "No exact matches in call to initializer "

3      

I am also trying to call sleepTime at the bottom of the app , but it is inside of calculateBedTime(). How do I declare the variable so that they can be used elsewhere? Also, do I have to also declare all the other variables: components, hour, minute, prediction?

import SwiftUI
struct ContentView: View {
    @State private var sleepAmount = 8.0
    @State private var wakeUp = defaultWakeTime
    @State private var coffeeAmount = 1

    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var showingAlert = false

    @State private var model = SleepCalculator()

    @State private var components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
    @State private var hour = (components.hour ?? 0) * 60 * 60
    @State private var minute = (components.minute ?? 0) * 60
    @State private var  prediction = try
        model.prediction(wake: Double(hour + minute) ?? 8, estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
    @State private var sleepTime = wakeUp - prediction.actualSleep

    var hours = [1..<9]
    var body: some View {
        NavigationView{
            Form{
                VStack(alignment: .leading, spacing: 0) {
    Text("When do you want to wake up?")
                    .font(.headline)
    DatePicker("Please enter a time", selection: $wakeUp,  displayedComponents: .hourAndMinute)
        .labelsHidden()
        .datePickerStyle(WheelDatePickerStyle())
                }
VStack(alignment: .leading, spacing: 0)
                {
Text("Desired Amount of Sleep")
    .font(.headline)

//    Picker(selection: $sleepAmount,  label: Text("")){
//        ForEach(1..<hours.count) {
//            Text(self.hours[$0])
//        }
//    }

//    Stepper (value: $sleepAmount, in: 4...12, step: 0.25){
//        Text("\(sleepAmount, specifier: "%g") hours")
//            }
                }
VStack(alignment: .leading, spacing: 0) {
        Text("Daily coffee intake")
            .font(.headline)
        Stepper (value: $coffeeAmount, in: 1...20){
        if coffeeAmount == 1 {
                Text ("1 cup")
                    } else {
        Text("\(coffeeAmount) cups")
                    }
                }
                }

    VStack(alignment: .leading, spacing: 0){
        Text("Your Ideal Bed Time is:\(sleepTime)")
            .font(Font.title.weight(.bold))
        //Text("\(sleepTime")
                }
        }
            .navigationTitle("Better Rest")
//          .navigationBarItems(trailing:
//            Button(action: calculateBedtime){
//                Text("Calculate")})
//            .alert(isPresented: $showingAlert) {
//                Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("OK")))}

        }
    }
   static var defaultWakeTime: Date{
        var components = DateComponents()
        components.hour = 7
        components.minute = 0
        return Calendar.current.date(from: components) ?? Date()
    }
    func calculateBedtime(){
        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
        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

            alertMessage = formatter.string (from: sleepTime)
            alertTitle = "Your ideal bedtime is ..."

        } catch {

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

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Do I make the @State variables?

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.