[Swift 1] Day 2 - Code Exercise Solution


#62

I originally had a “Bound value in conditional binding must be of Optional type” error. So I had to declare Double?() to get it to work. Not sure why.

@IBAction func buttonPressed(sender: AnyObject) {
    println("Button pressed!")
    if let width = Double?((widthTextField.text as NSString).doubleValue) {
        if let height = Double?((heightTextField.text as NSString).doubleValue) {
            println("Valid input \(width) x \(height)")
            
            var area = width * height
            outputLabel.text = "\(area)"
        }
    }
}

#63

@jonsaw

The if let syntax requires that the right side of the expression be optional, so you can unwrap it. You had to cast from a Double type to Double? (optional type) in order to make it a valid expression.

When NSString fails to convert a value, let’s say “dog” into a double value, it’ll return 0. There’s not Optional type return, the error case is just 0 – which can lead to bad input.

    var width = (dayTextField.text as NSString).doubleValue

Your expression works, but has the potential for bad input to be recognized as 0

I really recommend the NSNumberFormatter which has the ability to convert types and can provide optional types, which work well with the “if let” syntax.

    var numberFormatter = NSNumberFormatter()

    var numberString = "23"  // "invalid number"

    // Option 1: Use optional chaining to get the doubleValue from the NSNumber
    if let width = numberFormatter.numberFromString(numberString)?.doubleValue {
        // valid input (only numbers)
        println("Valid input: \(width)")
        
    } else {
        // invalid input (words, letters, mixed alphanumeric values)
    }
    
    if let width = numberFormatter.numberFromString(numberString) as? Double {
        println("Valid input: \(width)")
    } else {
        // invalid input (words, letters, mixed alphanumeric values)
    }

#64
@IBAction func buttonPressed(sender: AnyObject) {
    // println("Button Pressed")
    
    
    /*
    
    The following syntax seems to work for Doubles (or Floats).  If either input field is empty, that is interpreted as a zero.
    
    Alphabetical characters ( except for e ) are interpreted as follows:
    
    -- at the beginning of the text they are interpreted as zero and subsequent text is ignored
    
    -- in the middle of the text they act as number terminators and subsequent text is ignored
    
    -- at the end of text they are ignored
    
    A single "e" marks the beginning of a base ten exponent.
    
    There seems to be no need to test the return values for validity.
    
    */
    
    let width = Double((widthTextLabel!.text as NSString).doubleValue)
    let height = (heightTextLabel!.text as NSString).doubleValue
    
    println("valid input! \(width) x \(height)")

    var area = width * height

    println("area = \(area)")
    
    outputTextLabel.text = "\(area)"
    
}

#65

When I use that syntax, width becomes unresolved. I have Xcode (6.3.2).


#66

Which one ? Paul submitted 2 different ways of doing it, he just didn’t separate them, pick and use only one of them, for example:

 if let width = numberFormatter.numberFromString(numberString) as? Double {
        println("Valid input: \(width)")
    } else {
        println("Please enter valid a valid number!")// invalid input (words, letters, mixed alphanumeric values)
    }

#67

//
// ViewController.swift
// Area Calculator
//
// Created by RAND GERALD on 5/13/15.
// Copyright © 2015 RAND GERALD. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var widthTextLabel: UITextField!
@IBOutlet weak var heightTextLabel: UITextField!

@IBOutlet weak var outputAreaTextLabel: UILabel!
@IBOutlet weak var outputPerimeterTextLabel: 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 outputAreaText: String!
    var outputPerimeterText: String!
    var numberFormatter = NSNumberFormatter()

    if let width = numberFormatter.numberFromString(widthTextLabel.text) as? Double {

// println(“Valid input: (width)”)
if let height = numberFormatter.numberFromString(heightTextLabel.text) as? Double {
// println(“Valid input: (height)”)
let area = height * width
let perimeter = (height + width) * 2
// println(“area = (area)”)
println(“Perimeter: (perimeter)”)
outputAreaText = "Area: (area)"
outputPerimeterText = “Perimeter: (perimeter)”
} else {
println(“Please enter valid a valid height! [ (heightTextLabel.text) ]”)// invalid input (words, letters, mixed alphanumeric values)
outputAreaText = “Invalid or Missing Height”
}
} else {
println(“Please enter valid a valid width! [ (widthTextLabel.text) ]”) // invalid input (words, letters, mixed alphanumeric values)
outputAreaText = “Invalid or Missing Width”
}
outputAreaTextLabel.text = outputAreaText
outputPerimeterTextLabel.text = outputPerimeterText
}
}


#68

I had some trouble with this part of the challenge. I knew that it was either “FLOAT” or “DOUBLE”. I kept trying to just put in “toDouble” and it kept erroring out. So knowing that I have to add the function “toDouble” resolved the issue in record time. THX

// Adds new functionality to Swift’s String class
extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)!.doubleValue
}
}


#69
    //Defining where to get the values for width and height and accepting a string as a floating integer
    var width = (widthTextField.text as NSString).doubleValue
    var height = (heightTextField.text as NSString).doubleValue
    println("Valid input! \(width) x \(height)")
    
    
    //defining area by assigning it the value width * height
    var area = width * height
    var perimeter = 2 * (width + height)
    //Giving the outputLabel a value equal to area.
    areaOutputTextField.text = "\(area)"
    perimeterOutputField.text = "\(perimeter)"
  1. Int = integer. any number positive or negative ex: 9,1,-3
  2. String = a set of numbers and letters ex: Oct 11

#70

I am getting some errors when i alter the code. I figured some were relating to too many brackets. But now am getting this… can anyone tell me where i went wrong?


#71

You cannot convert a field to NSString. You have to use field’s attribute ‘text’ , so it’s widthTextField.text as NSString


#72

Thanks Ravenshore, yet another simple mistake from a late study session. Note to self, to check it again with clear outlook the next day. Thanks for the input.


#73

My code solution for double and perimeter is:

Answers:

  1. Int is short for Integer, a whole number (negative or positive)
  2. String is a set of letters, numbers and characters e.g. February 1st

#74

This is my piece of code for converting string to double and calculating perimeter:

   var width = NSString(string: widthTextField.text).doubleValue
    var height = NSString(string: heightTextField.text).doubleValue
    var area = width * height
    outputLabel.text = "\(area)"
    var perimeter = 2 * ( width + height)
    perimeterLabel.text = "\(perimeter)"

Questions
What does Int mean? Write down some examples.

Int is an integer value for example: 0,1,2,-1

What does String mean? Provide an example string using your next birthday.
A string is a collection of characters, for example: “My birthday is on July 19”