Applications open until spots fill up - Apply now.

Tip it up!

Tip it up!

April 16, 2017
Expand

Project: Tip Calculator in Swift 3

Linking your interface to code

Xcode makes it easy to connect your interface to code. Now that we've got an interface let's get it hooked up to our code files!

There are two main kinds of code connections: outlets, and actions. Outlets let you assign a variable in code to a component of your interface you have created in your storyboard to interact with that component in code. We will use that to read and set values from our interface. Actions let our code know when the user did certain things to an interface component that we want to react to.

Adding code connections

  1. Close the layout tree and attribute inspector to make some room.
  2. Open the assistant editor and make sure ViewController.swift is displayed by switching from "Preview" to "Automatic" in the dropdown menu above the assistant editor view window.
  3. Control-click (or right-click) drag from bill amount text field to under the class ViewController line and name the outlet billAmountField.
  4. Control-click (or right-click) drag from the tip selector text field and name the outlet tipSelector.
  5. Control-click (or right-click) drag from the tip amount text field and name the outlet tipAmountField.
  6. Control-click (or right-click) drag from the total amount text field and name the outlet totalAmountField.
  7. Control-click (or right-click) drag from the calculate button to the view controller. Choose Action and name it calculateTip.
  8. Add some space to clean up the file.

Adding the logic

Before we get started with the logic, we need to go over a new Swift concept! Let's talk about if let statements...

if let is a special statement that allows us to check the condition of a variable and perform actions based on that condition. In the code below, we are saying if you can cast billAmount to a Double and save it to a new variable called billAmount, then do nothing. However, if you cannot do this, then we should stop what we are doing and clear the fields". If the condition is met, then the function can continue.

Now that we have some outlets and actions, we can actually code our logic. Since this tutorial is about Xcode, not programming, we are going to give you the logic. Study the code below and make sure you understand the logic!

Overwrite the two new functions you created with the code below. You should type it out and make sure you understand the logic!

@IBAction func calculateTip(sender: AnyObject) {
    if let billAmount = Double(billAmountField.text!) {
        var tipPercentage = 0.0

        switch tipSelector.selectedSegmentIndex {
        case 0:
            tipPercentage = 0.15
        case 1:
            tipPercentage = 0.18
        case 2:
            tipPercentage = 0.20
        default:
            break
        }

        let roundedBillAmount = round(100 * billAmount) / 100
        let tipAmount = roundedBillAmount * tipPercentage
        let roundedTipAmount = round(100*tipAmount)/100
        let totalAmount = roundedBillAmount + roundedTipAmount

        if (!billAmountField.isEditing) {
            billAmountField.text = String(format: "%.2f", roundedBillAmount)
        }
        tipAmountField.text = String(format: "%.2f", roundedTipAmount)
        totalAmountField.text = String(format: "%.2f", totalAmount)
    } else {
        //show error
        billAmountField.text = ""
        tipAmountField.text = ""
        totalAmountField.text = ""
    }
}

Run it and give it a spin! Do you understand the code? Hover over the Solution below to see an explanation!

The calculateTip function starts off with a if let statement. If billAmount does not contain a number, it resets all of the fields.

If it does have a number, then the function continues. It uses a switch statement to read the segmented control and set tipPercentage. It then calculates the tipAmount and totalAmount. Finally, it updates the respective text fields.

Testing it out

Now that we have an interface, code connections, and logic... let's test it all out! Run the simulator and try calculating a tip :)

Looking good! Everything seems to work. On the next page, we'll make some small UI improvements before moving on to a more substantial app!

Feedback

If you have feedback on this tutorial or find any mistakes, please open issues on the GitHub Repository.

Join Make School

Prepare for your career as a founder or software developer

Apply Now

Talk to Us

If you have any questions, please send us an email

Email Us