Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

3.6 Class ViewController

Sections 3.6.1–3.6.7 present ViewController.swift, which contains class ViewController and several global utility functions that are used throughout the class to format NSDecimalNumbers as currency and to perform calculations using NSDecimalNumber objects. We modified the autogenerated comments that Xcode inserted at the beginning of the source code file.

3.6.1 import Declarations

Recall that to use features from the iOS 8 frameworks, you must import them into your Swift code. Throughout this app, we use the UIKit framework’s UI component classes. In Fig. 3.46, line 3 is an import declaration indicating that the program uses features from the UIKit framework. All import declarations must appear before any other Swift code (except comments) in your source-code files.

Fig. 3.40 | import declaration in ViewController.swift.

   1   // ViewController.swift
   2   // Implements the tip calculator's logic
   3   import UIKit

3.6.2 ViewController Class Definition

In Fig. 3.41, line 5—which was generated by the IDE when you created the project—begins a class definition for class ViewController.

Fig. 3.41 | ViewController class definition and properties.

   5   class ViewController: UIViewController {      

Keyword class and Class Names

The class keyword introduces a class definition and is immediately followed by the class name (ViewController). Class name identifiers use camel-case naming in which each word in the identifier begins with a capital letter. Class names (and other type names) begin with an initial uppercase letter and other identifiers begin with lowercase letters. Each new class you create becomes a new type that can be used to declare variables and create objects.

Class Body

A left brace (at the end of line 5), {, begins the body of every class definition. A corresponding right brace (at line 82 in Fig. 3.45), }, ends each class definition. By convention, the contents of a class’s body are indented.

Inheriting from Class UIViewController

The notation : UIViewController in line 5 indicates that class ViewController inherits from class UIViewController—the UIKit framework superclass of all view controllers. Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and enhancing them with new or modified capabilities. This relationship indicates that a ViewController is a UIViewController. It also ensures that ViewController has the basic capabilities that iOS expects in all view controllers, including methods like viewDidLoad (Section 3.6.5) that help iOS manage a view controller’s lifecycle. The class on the left of the : in line 5 is the subclass (derived class) and one on the right is the superclass (base class). Every scene has its own UIViewController subclass that defines the scene’s event handlers and other logic. Unlike some object-oriented programming languages, Swift classes are not required to directly or indirectly inherit from a common superclass.

3.6.3 ViewController’s @IBOutlet Properties

Figure 3.42 shows class ViewController’s nine @IBOutlet property declarations that were created by Interface Builder when you created the outlets in Section 3.4. Typically, you’ll define a class’s properties first followed by the class’s methods, but this is not required.

Fig. 3.42 | ViewController’s @IBOutlet properties.

   6       // properties for programmatically interacting with UI components
   7       @IBOutlet weak var billAmountLabel: UILabel!
   8       @IBOutlet weak var customTipPercentLabel1: UILabel!
   9       @IBOutlet weak var customTipPercentageSlider: UISlider!
  10       @IBOutlet weak var customTipPercentLabel2: UILabel!
  11       @IBOutlet weak var tip15Label: UILabel!
  12       @IBOutlet weak var total15Label: UILabel!
  13       @IBOutlet weak var tipCustomLabel: UILabel!
  14       @IBOutlet weak var totalCustomLabel: UILabel!
  15       @IBOutlet weak var inputTextField: UITextField!

@IBOutlet Property Declarations

The notation @IBOutlet indicates to Xcode that the property references a UI component in the app’s storyboard. When a scene loads, the UI component objects are created, an object of the corresponding view-controller class is created and the connections between the view controller’s outlet properties and the UI components are established. The connection information is stored in the storyboard. @IBOutlet properties are declared as variables using the var keyword, so that the storyboard can assign each UI component object’s reference to the appropriate outlet once the UI components and view controller object are created.

Automatic Reference Counting (ARC) and Property Attributes

Swift manages the memory for your app’s reference-type objects using automatic reference counting (ARC), which keeps track of how many references there are to a given object. The runtime can remove an object from memory only when its reference count becomes 0.

Property attributes can specify whether a class maintains an ownership or nonownership relationship with the referenced object. By default, properties in Swift create strong references to objects, indicating an ownership relationship. Every strong reference increments an object’s reference count by 1. When a strong reference no longer refers to an object, its reference count decrements by 1. The code that manages incrementing and decrementing the reference counts is inserted by the Swift compiler.

The @IBOutlet properties are declared as weak references, because the view controller does not own the UI components—the view defined by the storyboard that created them does. A weak reference does not affect the object’s reference count. A view controller does, however, have a strong reference to its view.

Type Annotations and Implicitly Unwrapped Optional Types

A type annotation specifies a variable’s or constant’s type. Type annotations are specified by following the variable’s or constant’s identifier with a colon (:) and a type name. For example, line 7 (Fig. 3.42) indicates that billAmountLabel is a UILabel!. Recall from Section 3.2.12 that the exclamation point indicates an implicitly unwrapped optional type and that variables of such types are initialized to nil by default. This allows the class to compile, because these @IBOutlet properties are initialized—they’ll be assigned actual UI component objects once the UI is created at runtime.

3.6.4 Other ViewController Properties

Figure 3.43 shows class ViewController’s other properties, which you should add below the @IBOutlet properties. Line 18 defines the constant decimal100 that’s initialized with an NSDecimalNumber object. Identifiers for Swift constants follow the same camel-case naming conventions as variables. Class NSDecimalNumber provides many initializers—this one receives a String parameter containing the initial value ("100.0"), then returns an NSDecimalNumber representing the corresponding numeric value. We’ll use decimal100 to calculate the custom tip percentage by dividing the slider’s value by 100.0. We’ll also use it to divide the user’s input by 100.0 for placing a decimal point in the bill amount that’s displayed at the top of the app. Initializers are commonly called constructors in many other object-oriented programming languages. Line 19 defines the constant decimal15Percent that’s initialized with an NSDecimalNumber object representing the value 0.15. We’ll use this to calculate the 15% tip.

Fig. 3.43 | ViewController class definition and properties.

  17       // NSDecimalNumber constants used in the calculateTip method
  18       let decimal100 = NSDecimalNumber(string: "100.0")        
  19       let decimal15Percent = NSDecimalNumber(string: "0.15")

Initializer Parameter Names Are Required

When initializing an object in Swift, you must specify each parameter’s name, followed by a colon (:) and the argument value. As you type your code, Xcode displays the parameter names for initializers and methods to help you write code quickly and correctly. Required parameter names in Swift are known as external parameter names.

Type Inference

Neither constant in Fig. 3.43 was declared with a type annotation. Like many popular languages, Swift has powerful type inference capabilities and can determine a constant’s or variable’s type from its initializer value. In lines 18–19, Swift infers from the initializers that both constants are NSDecimalNumbers.

3.6.5 Overridden UIViewController method viewDidLoad

Method viewDidLoad (Fig. 3.44)—which Xcode generated when it created class ViewController—is inherited from superclass UIViewController. You typically override it to define tasks that can be performed only after the view has been initialized. You should add lines 25–26 to the method.

Fig. 3.44 | Overridden UIViewController method viewDidLoad.

  21       // called when the view loads
  22      override func viewDidLoad() {
  23           super.viewDidLoad()
  25           // select inputTextField so keypad displays when the view loads
  26           inputTextField.becomeFirstResponder()
  27       }

A method definition begins with the keyword func (line 22) followed by the function’s name and parameter list enclosed in required parentheses, then the function’s body enclosed in braces ({ and }). The parameter list optionally contains a comma-separated list of parameters with type annotations. This function does not receive any parameters, so its parameter list is empty—you’ll see a method with parameters in Section 3.6.6. This method does not return a value, so it does not specify a return type—you’ll see how to specify return types in Section 3.6.7.

When overriding a superclass method, you declare it with keyword override preceding the keyword func, and the first statement in the method’s body typically uses the super keyword to invoke the superclass’s version of the method (line 23). The keyword super references the object of the class in which the method appears, but is used to access members inherited from the superclass.

Displaying the Numeric Keypad When the App Begins Executing

In this app, we want inputTextField to be the selected object when the app begins executing so that the numeric keypad is displayed immediately. To do this, we use property inputTextField to invoke the UITextField method becomeFirstResponder, which programmatically makes inputTextField the active component on the screen—as if the user touched it. You configured inputTextField such that when it’s selected, the numeric keypad is displayed, so line 26 displays this keypad when the view loads.

3.6.6 ViewController Action Method calculateTip

Method calculateTip (Fig. 3.45) is the action (as specified by @IBAction on line 31) that responds to the Text Field’s Editing Changed event and the Slider’s Value Changed event. Add the code in lines 32–81 to the body of calculateTip. (If you’re entering the Swift code as you read this section, you’ll get errors on several statements that perform NSDecimalNumber calculations using overloaded operators that you’ll define in Section 3.6.7.) The method takes one parameter. Each parameter’s name must be declared with a type annotation specifying the parameter’s type. When a view-controller object receives a message from a UI component, it also receives as an argument a reference to that component—the event’s sender. Parameter sender’s type—the Swift type AnyObject—represents any type of object and does not provide any information about the object. For this reason, the object’s type must be determined at runtime. This dynamic typing is used for actions (i.e., event handlers), because many different types of objects can generate events. In action methods that respond to events from multiple UI components, the sender is often used to determine which UI component the user interacted with (as we do in lines 42 and 57).

Fig. 3.45 | ViewController action method calculateTip.

  29       // called when the user edits the text in the inputTextField
  30       // or moves the customTipPercentageSlider's thumb
  31       @IBAction func calculateTip(sender: AnyObject) {
  32          let inputString = inputTextField.text // get user input
  34           // convert slider value to an NSDecimalNumber
  35           let sliderValue =
  36               NSDecimalNumber(integer: Int(customTipPercentageSlider.value))
  38           // divide sliderValue by decimal100 (100.0) to get tip %
  39           let customPercent = sliderValue / decimal100
  41           // did customTipPercentageSlider generate the event?
  42           if sender is UISlider {
  43               // thumb moved so update the Labels with new custom percent
  44               customTipPercentLabel1.text =
  45                  NSNumberFormatter.localizedStringFromNumber(customPercent,
  46                       numberStyle: NSNumberFormatterStyle.PercentStyle)     
  47               customTipPercentLabel2.text = customTipPercentLabel1.text
  48           }
  50          // if there is a bill amount, calculate tips and totals
  51           if !inputString.isEmpty {
  52               // convert to NSDecimalNumber and insert decimal point
  53               let billAmount =
  54                   NSDecimalNumber(string: inputString) / decimal100
  56               // did inputTextField generate the event?
  57               if sender is UITextField {
  58                   // update billAmountLabel with currency-formatted total
  59                   billAmountLabel.text = " " + formatAsCurrency(billAmount)
  61                   // calculate and display the 15% tip and total
  62                   let fifteenTip = billAmount * decimal15Percent
  63                   tip15Label.text = formatAsCurrency(fifteenTip)
  64                   total15Label.text =
  65                       formatAsCurrency(billAmount + fifteenTip)
  66               }
  68               // calculate custom tip and display custom tip and total
  69               let customTip = billAmount * customPercent
  70               tipCustomLabel.text = formatAsCurrency(customTip)
  71               totalCustomLabel.text =
  72                   formatAsCurrency(billAmount + customTip)
  73           }
  74           else { // clear all Labels
  75               billAmountLabel.text = ""
  76               tip15Label.text = ""
  77               total15Label.text = ""
  78               tipCustomLabel.text = ""
  79               totalCustomLabel.text = ""
  80           }
  81       }
  82   }

Getting the Current Values of inputTextField and customTipPercentageSlider

Line 32 stores the value of inputTextField’s text property—which contains the user’s input—in the local String variable inputString—Swift infers type String because UITextField’s text property is a String.

Lines 35–36 get the customTipPercentageSlider’s value property, which contains a Float value representing the Slider’s thumb position (a value from 0 to 30, as specified in Section 3.3.3). The value is a Float, so we could get tip percentages like, 3.1, 15.245, etc. This app uses only whole-number tip percentages, so we convert the value to an Int before using it to initialize the NSDecimalNumber object that’s assigned to local variable sliderValue. In this case, we use the NSDecimalNumber initializer that takes an Int value named integer.

Line 39 uses the overloaded division operator function that we define in Section 3.6.7 to divide sliderValue by 100 (decimal100). This creates an NSDecimalNumber representing the custom tip percentage that we’ll use in later calculations and that will be displayed as a locale-specific percentage String showing the current custom tip percentage.

Updating the Custom Tip Percentage Labels When the Slider Value Changes

Lines 42–48 update customTipPercentLabel1 and customTipPercentLabel2 when the Slider value changes. Line 42 determines whether the sender is a UISlider object, meaning that the user interacted with the customTipPercentageSlider. The is operator returns true if an object’s class is the same as, or has an is a (inheritance) relationship with, the class in the right operand.

We perform a similar test at line 57 to determine whether the user interacted with the inputTextField. Testing the sender argument like this enables you to perform different tasks, based on the component that caused the event.

Lines 44–46 set the customTipPercentLabel1’s text property to a locale-specific percentage String based on the device’s current locale. NSNumberFormatter class method localizedStringFromNumber returns a String representation of a formatted number. The method receives two arguments:

  • The first is the NSNumber to format. Class NSDecimalNumber is a subclass of NSNumber, so you can use an NSDecimalNumber anywhere that an NSNumber is expected.
  • The second argument (which has the external parameter name numberStyle) is a constant from the enumeration NSNumberFormatterStyle that represents the formatting to apply to the number—the PercentStyle constant indicates that the number should be formatted as a percentage. Because the second argument must be of type NSNumberFormatterStyle, Swift can infer information about the method’s argument. As such, it’s possible to write the expression NSNumberFormatterStyle.PercentStyle with the shorthand notation:

Line 47 assigns the same String to customTipPercentLabel2’s text property.

Updating the Tip and Total Labels

Lines 51–80 update the tip and total Labels that display the calculation results. Line 51 uses the Swift String type’s isEmpty property to ensure that inputString is not empty—that is, the user entered a bill amount. If so, lines 53–72 perform the tip and total calculations and update the corresponding Labels; otherwise, the inputTextField is empty and lines 75–79 clear all the tip and total Labels and the billAmountLabel by assigning the empty String literal ("") to their text properties.

Lines 53–54 use inputString to initialize an NSDecimalNumber, then divide it by 100 to place the decimal point in the bill amount—for example, if the user enters 5632, the amount used for calculating tips and totals is 56.32.

Lines 57–66 execute only if the event’s sender was a UITextField—that is, the user tapped keypad buttons to enter or remove a digit in this app’s inputTextField. Line 59 displays the currency-formatted bill amount in billAmountLabel by calling the formatAsCurrency method (defined in Section 3.6.7). Line 62 calculates the 15% tip amount by using an overloaded multiplication operator function for NSDecimalNumbers (defined in Section 3.6.7). Then line 63 displays the currency-formatted value in the tip15Label. Next, lines 64–65 calculates and displays the total amount for a 15% tip by using an overloaded addition operator function for NSDecimalNumbers (defined in Section 3.6.7) to perform the calculation, then passing the result to the formatAsCurrency function. Lines 69–72 calculate and display the custom tip and total amounts based on the custom tip percentage.

Why an External Name Is Not Required for a Method’s First Argument

You might be wondering why we did not provide a parameter name for the first argument in the method call at lines 45–46. For method calls, Swift requires external parameter names for all parameters after the first parameter. Apple’s reasoning for this is that they want method calls to read like sentences. A method’s name should refer to the first parameter, and each subsequent parameter should have a name that’s specified as part of the method call.

3.6.7 Global Utility Functions Defined in ViewController.swift

Figure 3.46 contains several global utility functions used throughout class ViewController. Add lines 84–103 after the closing right brace of class ViewController.

Fig. 3.46 | ViewController.swift global utility and overloaded operator functions.

  84   // convert a numeric value to localized currency string
  85   func formatAsCurrency(number: NSNumber) -> String {                              
  86       return NSNumberFormatter.localizedStringFromNumber(                      
  87           number, numberStyle: NSNumberFormatterStyle.CurrencyStyle)
  88   }                                                                 
  90   // overloaded + operator to add NSDecimalNumbers
  91   func +(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber {
  92       return left.decimalNumberByAdding(right)                                                            
  93   }                                                                                                                                                  
  95   // overloaded * operator to multiply NSDecimalNumbers
  96   func *(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber {
  97       return left.decimalNumberByMultiplyingBy(right)
  98   }
  100  // overloaded / operator to divide NSDecimalNumbers
  101  func /(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber {
  102      return left.decimalNumberByDividingBy(right)
  103  }

Defining a Function—formatAsCurrency

Lines 85–88 define the function formatAsCurrency. Like a method definition, a function definition begins with the keyword func (line 85) followed by the function’s name and parameter list enclosed in required parentheses, then the function’s body enclosed in braces ({ and }). The primary difference between a method and a function is that a method is defined in the body of a class definition (or struct or enum definition). Function formatAsCurrency receives one parameter (number) of type NSNumber (from the Foundation framework).

A function may also specify a return type by following the parameter list with -> and the type the function returns—this function returns a String. A function that does not specify a return type does not return a value—if you prefer to be explicit, you can specify the return type Void. A function with a return type uses a return statement (line 86) to pass a result back to its caller.

We use formatAsCurrency throughout class ViewController to format NSDecimal-Numbers as locale-specific currency Strings. NSDecimalNumber is a subclass of NSNumber, so any NSDecimalNumber can be passed as an argument to this function. An NSNumber parameter can also receive as an argument any Swift numeric type value—such types are automatically bridged by the runtime to type NSNumber.

Lines 86–87 invoke NSNumberFormatter class method localizedStringFromNumber, which returns a locale-specific String representation of a number. This method receives as arguments the NSNumber to format—formatAsCurrency’s number parameter—and a constant from the NSNumberFormatterStyle enum that specifies the formatting style—the constant CurrencyStyle specifies that a locale-specific currency format should be used. Once again, we could have specified the second argument as .CurrencyStyle, because Swift knows that the numberStyle parameter must be a constant from the NSNumberFormatterStyle enumeration and thus can infer the constant’s type.

Defining Overloaded Operator Functions for Adding, Subtracting and Multiplying NSDecimalNumbers

Lines 91–93, 96–98 and 101–103 create global functions that overload the addition (+), multiplication (*) and division (/) operators, respectively. Global functions (also called free functions or just functions) are defined outside a type definition (such as a class). These functions enable us to:

  • add two NSDecimalNumbers with the + operator (lines 65 and 72 of Fig. 3.45)
  • multiply two NSDecimalNumbers with the * operator (lines 62 and 69 of Fig. 3.45)
  • divide two NSDecimalNumbers with the / operator (lines 39 and 54 of Fig. 3.45)

Overloaded operator functions are defined like other global functions, but the function name is the symbol of the operator being overloaded (Fig. 3.46 lines 91, 96 and 101). Each of these functions receives two NSDecimalNumbers representing the operator’s left and right operands.

The addition (+) operator function (lines 91–93) returns the result of invoking NSDecimalNumber instance method decimalNumberByAdding on the left operand with the right operand as the method’s argument—this adds the operands. The multiplication (*) operator function (lines 96–98) returns the result of invoking NSDecimalNumber instance method decimalNumberByMultiplyingBy on the left operand with the right operand as the method’s argument—this multiplies the operands. The division (/) operator function (lines 101–103) returns the result of invoking NSDecimalNumber instance method decimalNumberByDividingBy on the left operand with the right operand as the method’s argument—this divides the left operand by the right operand. Since each of these NSDecimalNumber instance methods receives only one parameter, the parameter’s name is not required in the method call. Unlike initializers and methods, a global function’s parameter names are not external parameter names and are not required in function calls unless they’re are explicitly defined as external parameter names in the function’s definition.

  • + Share This
  • 🔖 Save To Your Account