[Swift 1] Day 2 - Code Exercise Solution


#21

I’ll remember to use Number Pad in these situations, thanks.


#22

Hi, thank you for that second day.
Here is my code for today :

@IBAction func calculate(sender: UIButton) {

let numberFormatter = NSNumberFormatter()
if let width = numberFormatter.numberFromString(widthTextField.text) as? Double {
    if let height = numberFormatter.numberFromString(heightTextField.text) as? Double {
        areaLabel.text = "\(width * height)"
        perimeterLabel.text = "\(2 * width + 2 * height)"
    }
}
}

For the answers :
Int are integers, positive or negative, with a limit in both ends.
Strings means “string” of characters. They are an enumeration so we can cycle in a string and it’s pretty cool :slight_smile:

var thanks = "Thank you Paul"
for char in thanks { println(char) }

#23

Here is my code for Day2

Let me know if someone finds any errors. Thanks!

Regards
Ranjith


#24

Extension of Day 2

Hey guys, here is how I added the rectangle with “Width” and “Height”.
In Main.storyboard:

  1. Create an image or something to represent a rectangle.

  2. Create labels:
    Right Width Label and Right Width Output (Label also)
    Left Width Label and Left Width Output (Label also)
    Top Height Label and Top Height Output (Label)
    Bottom Height Label and Bottom Height Output (Label)
    In ViewController:
    1.Connect the width and height text fields to the view controller (Use a name that will help you, EX: I used showWidthTextField again, except add the as Connection - Action, not Outlet . REMEMBER when adding these new text field connections: Select Event - Editing Changed. Now, inside of your text field actions, use the code bellow. You are using the same double values you should have used earlier to calculate area/perimeter.

    @IBAction func showWidthTextField(sender: UITextField) {

     var width = (widthTextField.text as NSString).doubleValue
     var height = (heightTextField.text as NSString).doubleValue
     widthTopLabel.text = "\(width)"
     widthBottomLabel.text = "\(width)"
    

    }

    @IBAction func showHeightTextField(sender: UITextField) {

     var width = (widthTextField.text as NSString).doubleValue
     var height = (heightTextField.text as NSString).doubleValue
     heightLeftLabel.text = "\(height)"
     heightRightLabel.text = "\(height)"
    

}

@PaulSolt P. S. I learned to how to use UILabels for any output in Paul’s Objective-C course.


#25

Question 1: Int is an integer, a whole number, including negative. example 1, -1, 33, -33.
Question 2: A string is a collection of characters. Example: “May 12”

I went Fernando’s route with the double numbers and perimeter addition.

extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)!.doubleValue
}
}
@IBAction func buttonPressed(sender: AnyObject) {

    if let width = widthTextField.text.toDouble()
    {
        if let height = heightTextField.text.toDouble()
        {
            // Calculate area
            var area = width * height
            outputLabel.text = "\(area)"
            
            // Calculate perimeter
            var perimeter = 2 * (width + height)
            perimeterLabel.text = "\(perimeter)"
        }
    }
}

}


#26

You could technically still paste-in non-numeric code… so the keyboard isn’t a catch all.


#27

Can you post more code? I’d like to see your full code file, there might be something else wrong.

It appears that perimeter is an optional value, or somewhere else in your code you have one.

You can’t use the value if it’s bad, so it’s good to check.

Granted I haven’t discussed this yet, look at some of the other solutions.


#28

Ah, very true… Good point.


#29

Thank you Paul! here it is:
//
// ViewController.swift
// Area Calculator
//
// Created by H Choo on 10/8/14.
// Copyright © 2014 H Choo. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var widthTextField: UITextField!
@IBOutlet weak var heightTextField: UITextField!

@IBOutlet weak var outputLabel: UILabel!
@IBOutlet weak var perimeterLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

@IBAction func buttonPressed(sender: AnyObject) {
    
    println("button pressed")
    
    
// when using decimal numbers 
    
    var width = (widthTextField.text as NSString).doubleValue
    var height = (heightTextField.text as NSString).doubleValue
    
    var area = width * height
    
    outputLabel.text = "\(area)"
   
    
// when not using decimal numbers

// println(“button pressed”)
//
// if let width = widthTextField.text.toInt(){
// if let height = heightTextField.text.toInt(){
// println(“valid input! (width) x (height)”)
//
// var area = width * height
// areaLabel.text = “(area)”
//
// }
// }
//

}

@IBAction func perimeterPressed(sender: AnyObject) {
    
    println("perimeterButtonPressed")
    
    var width = (widthTextField.text as NSString).doubleValue
    var height = (heightTextField.text as NSString).doubleValue
    
    var perimeter = 2 * (width + height)
    
    perimeterLabel.text = "\(perimeter)"
    
    
}

}


#30

This is mine, but I found that it doesn’t actually calculate quite correctly when you are using decimal point values. Is that because of the floats ? Can anyone test it and let me know ?

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

import UIKit

class ViewController: UIViewController {

   
    @IBOutlet weak var widthTextField: UITextField!
    
    @IBOutlet weak var heightTextField: UITextField!
    
    @IBOutlet weak var outputLabel: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  
    
    
    @IBAction func buttonPressedPerimeter(sender: AnyObject) {
        
        println("button pressed P")
        
        
        var width = (widthTextField.text as NSString).floatValue
        var height = (heightTextField.text as NSString).floatValue
        
        println("Valid Input! \(width) x \(height)")
        
        var perimeter = 2 * (width + height)
        outputLabel.text = "Perimeter is \(perimeter)"
        outputLabel.textColor = UIColor(red: (50/255.0), green: (140/255.0), blue: (5/255.0), alpha: 1.0)
        
        
    }
    
    @IBAction func buttonPressed(sender: AnyObject) {
        
        println("button pressed")
        
        
        var width = (widthTextField.text as NSString).floatValue
        var height = (heightTextField.text as NSString).floatValue
        
       
                
                println("Valid Input! \(width) x \(height)")
                
                var area = width * height
                
                outputLabel.text = "Area is \(area)"
                outputLabel.textColor = UIColor(red: (200/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0)
        
            
            
        
        
    }

    
}

#31

I guess I found my own answer:

http://stackoverflow.com/questions/5098558/float-vs-double-precision

So, the lesson is - don’t use floats with decimal calculations ? When you want precision ?


#32

Double for accuracy – like aerospace, rocket ships, and money.

Float is good for game character positions or approximate data.


#33

Can you .zip up the project and post it, or email me at PaulSolt@iPhoneDev.tv

The code seems ok, but I need to see the interface to test it out.


#34

Here is the link:

https://drive.google.com/file/d/0B00fLVsdls5VTGxEalhzM29XQXc/view?usp=sharing


#35

Hi Ryan,

Thanks for sharing.

May I know the Rectangle Object is image view in the story board? or you insert by coding? I am lost.


#36

Hi @Jason_zhou,
I used a UiView, I think it’s the second to last item on the list where you get bottoms, labels, etc. I set the background color to blue. You size the view (representing a square/rectangle) to your liking.


#38

Here’s my app code:

An “Int” is an integer which is any whole number; a string is a block of text that can contain numbers, letters and punctuation. A string representing my birthday would be “October 27” or it could be “10/27”


#39

Int = integer which is a whole number, including negative.
A string is a combination of characters consisting of letters and number October 18

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var widthTextField: UITextField!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var outputLabel: UILabel!
@IBOutlet weak var perimeterTextField: UITextField!
@IBOutlet weak var perimeterOutput: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

@IBAction func buttonPressed(sender: AnyObject) {
    
    println("Button Pressed")
    
    var width = (widthTextField.text as NSString).doubleValue
    var height = (heightTextField.text as NSString).doubleValue
    
            println("valid input! \(width) x \(height)")
            
            var area = width * height
            outputLabel.text = "\(area)"
  
            var perimeter = 2 * (width + height)
            perimeterOutput.text = "\(perimeter)"
    
        }

}


#40

Int = integer - a whole number including negative numbers
String = a combination of characters (letters and numbers) for example: October 21


#41

int is a whole number (positive or negative) and a string is a combination of numbers and letters.

here is my code for the exercise: also, just to experiment I added a third text field and label (depth) to see if I could get it to calculate volume, which worked perfectly!

class ViewController: UIViewController {


@IBOutlet weak var widthTextField: UITextField!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var depthTextField: UITextField!
@IBOutlet weak var outputLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

@IBAction func buttonPress(sender: AnyObject) {
    
    println("button pressed")
    
    // convert string to double
    let width = NSString(string: widthTextField.text).doubleValue
    let height = NSString(string: heightTextField.text).doubleValue
    let depth = NSString(string: depthTextField.text).doubleValue
    
    println("Valid input! \(width) x \(height) x \(depth)")
    
    var volume = width * height * depth
    outputLabel.text = "\(volume)"
    
    if let width = widthTextField.text.toInt() {
        
        if let height = heightTextField.text.toInt() {
            
           if let depth = depthTextField.text.toInt(){
            
            println("Valid input! \(width) x \(height) x \(depth)")

            var volume = width * height * depth
            outputLabel.text = "\(volume)"
                
            }
    
        }
        
    }
    
    
}

}