Sunday, May 15, 2016

Swift Tutorial - Part 6 - Tip Calculator App, UISlider, if let

Tip Calculator App, UISlider, if let


Video Description 
The purpose of this app is to get more familiar with the concept of IBAction and IBOutlet. We also introduced UISlider and how we can get the value out of it.

if let

There is an important concept in swift that is mentioned in this part of tutorial and it's nothing but "if let". Whenever you unwrap an optional, you should be very careful because if the value that you are trying to unwrap is equal nil or null, it will throws an exception and crash your app. In order to be safe while we unwrap an object, we can use if let logic like bellow:
if let variableName = someValue {
            //someValue is not nil and it's safe to unwrap
        }
        else {
            //someValue is nil and cannot be unwrapped
        }

In the above statement, if someValue is not nil it will go to the first bracket but if it's nill, it will go to the else statement. This concept is highly recommended for unwrapping the values that we are not sure if it's nil or not.

Source Code for the app

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var billAmountField: UITextField!
    @IBOutlet weak var tipPercentageLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var tipAmountLabel: UILabel!
    @IBOutlet weak var tpSlider: UISlider!
    
    @IBAction func calculatePressed(sender: UIButton) {
        calculateTip()
    }
    
    @IBAction func sliderChanged(sender: UISlider) {
        tipPercentageLabel.text! = "Tip Percentage " + String(Int(sender.value)) + "%"
        calculateTip()
    }
    
    func calculateTip() {
        var tipAmount = Float()
        var total = Float()
        if let billAmount = Float(billAmountField.text!) {
            tipAmount = billAmount * tpSlider.value/100
            total = tipAmount + billAmount
        }
        else {
            tipAmount = 0
            total = 0
        }
        tipAmountLabel.text! = String(tipAmount)
        totalLabel.text! = String(total)
    }
}

Download

Download Tip Calculator App from here