[Swift 1] Day 9 - Code Exercise Solution


#1

Post your code solutions to the Day 9 Code Exercise here.

Share code, screenshots, or videos of your app in progress.

What do you want to learn next?


#2
  1. Make a function to calculate how many pounds (kg) of turkey to buy for dinner.
  2. Make a function to calculate how many hours to thaw a frozen turkey in the fridge.
  3. Make a function to calculate the time to cook a turkey.
  4. Create an iPhone app UI to display the different fields.
  5. Extra 1: Add UISlider elements to control the number of people
  6. Extra 2: Automatically recalculate the values as the number of people changes.

Code is here.

Demo:

Trivia: we’ll make great pets.

Where would the Maps app use a function?

Everywhere. Say, when you click here (assuming that the IBAction calls a function).

This is actually a tricky question. This kind of helped me on understanding the difference. Kind of.

What is a parameter?

One or more named, typed values that a function takes as input. In

func add(a: Int, b: Int) -> Int? { return a + b }

a and b are parameters.

What is a return type?

A type of value that the function will pass back as output when it is done.

In the above function, the return type is an Int. The (a + b).

What is an argument?

It’s the actual values passed in to a function. E.g:

let sum = add(3, 5)

3 and 5 are arguments.

How do functions help with writing code?

I’d say code reuse (you can reuse a function many times in different parts of the code), readability (it’s easier to understand a code that clearly separates responsibilities than those in which everything is done in one huge block) and maintainability (it’s easy to add or remove features and fix bugs when the code is divided in little chunks).


#3

Hey there,

here is my solution for the code exercise. This one freaked me out. At first I could’t get the weight var out of the methods. Took me a while to get that managed. Besides I didn’t really get the time to be displayed readable. Hope we get a tutorial for this soon?

Code is here: https://gist.github.com/thedan84/10ffff42850001cef520#file-turkey-cooking-calculator


#4

Hi everyone!
My code is here

It wasn’t easy to convert those minutes to something readable! It took a while. I first transform minutes to hours+minute and then I just strip the .0 at the end before outputting to my labels. M calculation seems to match with Paul’s number in the example screenshot ( for 5 people > 7.5lb, 45h and 1:52 hours ).


#5

Alrighty, here we go, not sure if code is optimized as it should be, but it works :)))

(just noticed i messed up some of my constrains moving things around, but way too sleepy to fix it now :slight_smile: )


Here is the code:

//
//  ViewController.swift
//  Turkey Calculator
//
//  Created by Razvigor Andreev on 10/15/14.
//  Copyright (c) 2014 Razvigor Andreev. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    
    //sliders
    
    @IBOutlet weak var slider: UISlider!
    @IBAction func sliderMoved(sender: AnyObject) {
        update()
        }
    
    //labels
    
    @IBOutlet weak var weightLabel: UILabel!
    @IBOutlet weak var thawLabel: UILabel!
    @IBOutlet weak var bakeLabel: UILabel!
    @IBOutlet weak var peopleLabel: UILabel!
    
    // iVars
    
    let thawFactor = 90.0 // minutes per LB for thawing
    let bakeFactor = 30.0  // min per LB
    
    var people = Int(1)
    var weight = 1.0
    var time = 1.0
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.view.backgroundColor = UIColor(patternImage: UIImage(named: "texture1.png"))
        
        update ()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    
    func update () {
        
        
        people = Int(slider.value)
        peopleLabel.text = "\(people)"
        
        weight = Double(Double(people) * 0.8)
        time = (weight * Double(people))
        
        calcWeight()
        calcTime()
        bakeTime()
        
        
        
    }
    
    func calcWeight () {
    
    
    weightLabel.text = ("\(Double(people) * 0.8) lb")
    
    }
    
    func calcTime () {
        
        let thawTime = (thawFactor * weight)
        let thawHours = floor(thawTime/60)
        let thawMinutes = round(thawTime - thawHours * 60)
        
        thawLabel.text = ("\(thawHours) hrs, \(thawMinutes) min")
        
    }
    
    func bakeTime () {
        
        let timeBake = (bakeFactor * weight)
        let hoursBake = floor(timeBake/60)
        let minutesBake = round(timeBake - hoursBake*60)
        
        bakeLabel.text = ("\(hoursBake) hrs, \(minutesBake) min")
        
    }

}

#6

Here is my code for today.

theUI :

The code :

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var numberOfGuestsLabel: UILabel!
@IBOutlet weak var turkeySizeLabel: UILabel!
@IBOutlet weak var thawTimeLabel: UILabel!
@IBOutlet weak var cookTimeLabel: UILabel!

@IBOutlet weak var numberOfPersonSlider: UISlider!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    
numberOfPersonSlider.addTarget(self, action: "numberOfPersonChanged:", forControlEvents: UIControlEvents.ValueChanged)
numberOfPersonSlider.value = 1
refreshCalculation(1)
    
    
    
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func numberOfPersonChanged (slider:UISlider) {
    
    refreshCalculation(Int(round(slider.value)))
    
}

func refreshCalculation(guest:Int) {
    numberOfGuestsLabel.text = "\(guest)"
    
    let turkeySize = getTurkeySize(guest)
    turkeySizeLabel.text = "\(turkeySize) Lbs"

    thawTimeLabel.text = getThawTime(turkeySize)
    cookTimeLabel.text = getCookTime(turkeySize)
    
}

func getTurkeySize(numberOfGuest:Int) -> Double {
    
    return Double(Double(numberOfGuest) * 1.5)
}

func getThawTime(size:Double) -> String {
    
    let thawTimeInHours:Double = size * 24 / 4
    
    let days = Int(thawTimeInHours / 24) > 1 ? "\(Int(thawTimeInHours / 24)) days ":"\(Int(thawTimeInHours / 24)) day "
    let hours = Int(thawTimeInHours % 24) > 1 ? "\(Int(thawTimeInHours % 24)) hours":"\(Int(thawTimeInHours % 24)) hour"
    
    return days + hours
    
}


func getCookTime(size:Double) -> String {
    
    let cookTimeInMinutes:Double = size * 15
    
    let hours = Int(cookTimeInMinutes / 60) > 1 ? "\(Int(cookTimeInMinutes / 60)) hours ":"\(Int(cookTimeInMinutes / 60)) hour "
    let minutes = Int(cookTimeInMinutes % 60) > 1 ? "\(Int(cookTimeInMinutes % 60)) minutes":"\(Int(cookTimeInMinutes % 60)) minute"
    
    return hours + minutes
}
}

#7

Hi there,
Here my code and a screen.

import UIKit

var sliderGuest = 5

func calculateHowManyPounds(persons: Int) -> Double {
    var pounds = Double(persons) * 1.5

    return pounds
}

func calculateHowManyHours(pounds: Double) -> String {
    var time = pounds * 24 / 4
    let days = Int(time / 24) > 1 ? "\(Int(time / 24)) Days ":"\(Int(time / 24)) Day "
    let hours = Int(time % 24) > 1 ? "\(Int(time % 24)) Hours ":"\(Int(time % 24)) Hour"

    return days + hours
}

func calculateTimeToCook(pounds: Double) -> String {
    var minutes = 15 * pounds
    let hour = Int(minutes / 60) > 1 ? "\(Int(minutes / 60)) Hours ":"\(Int(minutes / 60)) Hour "
    let minute = Int(minutes % 60) > 1 ? "\(Int(minutes % 60)) Minutes ":"\(Int(minutes % 60)) Minute"
    
    return hour + minute
}


class ViewController: UIViewController {
    @IBOutlet weak var turkeySizeLabel: UILabel!
    @IBOutlet weak var thawTimeLabel: UILabel!
    @IBOutlet weak var cookTimeLabel: UILabel!
    @IBOutlet weak var numberOfGuestLabel: UILabel!
    @IBOutlet weak var guestSlider: UISlider!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        guestSlider.addTarget(self, action: "numberOfGuestChaged:", forControlEvents: UIControlEvents.ValueChanged)
        view.backgroundColor = UIColor(red: 255/255.0, green: 224/255.0, blue: 186/255.0, alpha: 1)
    }


    func numberOfGuestChaged(slider: UISlider) {
        turkeySizeLabel.text = " \(calculateHowManyPounds(sliderGuest)) Lbs"
        thawTimeLabel.text = " \(calculateHowManyHours(calculateHowManyPounds(sliderGuest)))"
        cookTimeLabel.text = " \(calculateTimeToCook(calculateHowManyPounds(sliderGuest)))"
    }
    

    @IBAction func guestSliderChanged(sender: UISlider) {
        sliderGuest = Int(sender.value)
        numberOfGuestLabel.text = " \(sliderGuest)"
    }
}

#8

Awesome stuff :slight_smile:
I see most people used a different method for calculating Hrs and Min than me.

Paul, could you maybe briefly go through the differences ? Also can you make an example of displaying the Hrs/Min using the NSCalendar/Date ?


#9

those functions remind me something :slight_smile:


#10

Yes, I really was very useful to see the code of each. Thanks,


#11

A question came to my mind while I was reading this code. What is the difference among these two declarations:

numberOfPersonSlider.addTarget(self, action: "numberOfPersonChanged:", forControlEvents: UIControlEvents.ValueChanged)

versus

@IBAction func numberOfPersonChanged(sender: AnyObject) {
        
    }// this one comes from dragging slider from storyboard to viewcontroller.swift

#12

No difference in my opinion. First one is how to create it programmatically. Which is the way to go if you want to later change the slider around.


#13

@IamMashed @ravenshore

They are the same, just two ways to create the same event code.

One is by the Storyboard connection and the other is code that you can insert in your viewDidLoad() method. The Storyboard connection will automatically create that code connection in the UI file and will load it when your app starts (it’s a little magical).


#14

I’ll take a look at the differences and put together a video if that would help.

There are different ways to get the same result using different classes.


#15

Notebook activity:

  1. Maps app would use a function to drop a pin to a specific location or say add an address as a string to a dictionary or array of addresses.
  2. Parameters are inputs inside the function that are worked on to be returned. The argument is entered as the parameter and returned as the value of the function.
  3. Return type is the information that is the result of the arguments entered into the function parameters.
    4)Functions are blocks of code that help break down the code into little chunks. These chunks are more useful to be called in different places and multiple times instead of writing it all out again and again.
  4. argument is the things you enter into the function as parameters.

My code for the app can be seen here Github link

Overall its ok, I managed to get the slider to work with the labels being updated. If I was to further work on it I would format the time to show in a proper format plus some logic about minimum time cooking etc.

Another Cool things I learnt, I have a good idea about style formatting so the code looks better. The link for that is Style guide

indent preformatted text by 4 spaces`indent preformatted text by 4 spaces`
//
//  ViewController.swift
//  Day 9 Turkey Cooking Helper
//
//  Created by Sasha Akhavan-Zanjani on 15/03/2015.
//  Copyright (c) 2015 Sasha Akhavan-Zanjani. All rights reserved.
//

import UIKit


//  Variables

  var numberOfPeople = Double()
  var cookingTime = Double()
  var timeMinutes = Double()
  var timeHours = Double()
  var weight = Double()
  var turkeyTimeToThaw = Double()
  var peopleValue = Double()

class ViewController: UIViewController {

  
  //  Labels and sliders
  @IBOutlet weak var turkeySizeLabel: UILabel!
  @IBOutlet weak var thawTimeLabel: UILabel!
  @IBOutlet weak var cookTimeLabel: UILabel!
  @IBOutlet weak var numberOfPeopleLabel: UILabel!
  @IBOutlet weak var numberOfPeople: UISlider!
  
  
  //    (0.7 kg/person)
  func howMuchTurkey(#people: Double) -> Double {
    return people * 0.7
  }
  
  //    Use 24 hours = 1,440 minutes per 4 lbs (1.8kg) of turkey
  func howManyMinutesToThaw(#weight: Double) -> Double {
    return weight * 800
  }
  
  //    Use 15 minutes per 1 lb (0.45kg) of turkey
  func howLongToCook(#weight: Double) -> Double {
    return weight * 33.33
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
  }
  
  @IBAction func numberOfPeopleSlider(sender: UISlider) {
    var sliderValue = Double(sender.value)

    peopleValue = sliderValue
    let currentValue = Int(peopleValue)
    numberOfPeopleLabel.text = " \(currentValue)"
   
    var turkeySize = howMuchTurkey(people: peopleValue)
    var turkeyTimeToThaw = howManyMinutesToThaw(weight: turkeySize)
    var cookingTime = howLongToCook(weight: turkeySize)

    //    change minutes to hours and minutes
    
    let thawRounded = Int(round(turkeyTimeToThaw / 60))
    let cookRounded = Int(floor(cookingTime / 60))
    let sizeRounded = Int(round(turkeySize))
    
    turkeySizeLabel.text = " \(sizeRounded) kg"
    thawTimeLabel.text = " \(thawRounded) hours"
    cookTimeLabel.text = " \(cookRounded) hours"

  }
  
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
      }
       
}

#16

@sashaz this is great! Keep it up – you’re making a ton of progress!


#17

Hi, here is my code and App screen.

code