Home > Articles > Programming > General Programming/Other Languages

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

3.2 Technologies Overview

This section introduces the Xcode, Interface Builder and Swift features you’ll use to build the Tip Calculator app.

3.2.1 Swift Programming

Swift is Apple’s programming language of the future for iOS and OS X development. The app’s code uses Swift data types, operators, control statements and keywords, and other language features, including functions, overloaded operators, type inference, variables, constants and more. We’ll introduce Swift object-oriented programming features, including objects, classes, inheritance, methods and properties. We’ll explain each new Swift feature as we encounter it in the context of the app. Swift is based on many of today’s popular programming languages, so much of the syntax will be familiar to programmers who use C-based programming languages, such as Objective-C, Java, C# and C++. For a detailed introduction to Swift, visit:

https://developer.apple.com/library/ios/documentation/Swift/
   Conceptual/Swift_Programming_Language/                   

3.2.2 Swift Apps and the Cocoa Touch® Frameworks

A great strength of iOS 8 is its rich set of prebuilt components that you can reuse rather than “reinventing the wheel.” These capabilities are grouped into iOS’s Cocoa Touch frameworks. These powerful libraries help you create apps that meet Apple’s requirements for the look-and-feel of iOS apps. The frameworks are written mainly in Objective-C (some are written in C). Apple has indicated that new frameworks will be developed in Swift.

Foundation Framework

The Foundation framework includes classes for basic types, storing data, working with text and strings, file-system access, calculating differences in dates and times, inter-app notifications and much more. In this app, you’ll use Foundation’s NSDecimalNumber and NSNumberFormatter classes. Foundation’s class names begin with the prefix NS, because this framework originated in the NextStep operating system. Throughout the book, we’ll use many Foundation framework features—for more information, visit:

http://bit.ly/iOSFoundationFramework

UIKit Framework

Cocoa Touch’s UIKit framework includes multi-touch UI components appropriate for mobile apps, event handling (that is, responding to user interactions with the UI) and more. You’ll use many UIKit features throughout this book.

Other Cocoa Touch Frameworks

Figure 3.2 lists the Cocoa Touch frameworks. You’ll learn features from many of these frameworks in this book and in iOS 8 for Programmers: An App-Driven Approach, Volume 2. For more information on these frameworks, see the iOS Developer Library Reference (http://developer.apple.com/ios).

Fig. 3.2

Fig. 3.2 | List of Cocoa Touch frameworks.

3.2.3 Using the UIKit and Foundation Frameworks in Swift Code

To use UIKit framework classes (or classes from any other existing framework), you must import the framework into each source-code file that uses it (as we do in Section 3.6.1). This exposes the framework’s capabilities so that you can access them in Swift code. In addition to UIKit framework UI components, this app also uses various classes from the Foundation framework, such as NSDecimalNumber and NSNumberFormatter. We do not import the Foundation framework—its features are available to your code because the UIKit framework indirectly imports the Foundation framework.

3.2.4 Creating Labels, a Text Field and a Slider with Interface Builder

You’ll again use Interface Builder and auto layout to design this app’s UI, which consists of Labels for displaying information, a Slider for selecting a custom tip percentage and a Text Field for receiving the user input. Several Labels are configured identically—we’ll show how to duplicate components in Interface Builder, so you can build UIs faster. Labels, the Slider and the Text Field are objects of classes UILabel, UISlider and UITextField, respectively, and are part the UIKit framework that’s included with each app project you create.

3.2.5 View Controllers

Each scene you define is managed by a view controller object that determines what information is displayed. iPad apps sometimes use multiple view controllers in one scene to make better use of the larger screen size. Each scene represents a view that contains the UI components displayed on the screen. The view controller also specifies how user interactions with the scene are processed. Class UIViewController defines the basic view controller capabilities. Each view controller you create (or that’s created when you base a new app on one of Xcode’s app templates) inherits from UIViewController or one of its subclasses. In this app, Xcode creates the class ViewController to manage the app’s scene, and you’ll place additional code into that class to implement the Tip Calculator’s logic.

3.2.6 Linking UI Components to Your Swift Code

Properties

You’ll use Interface Builder to generate properties in your view controller for programmatically interacting with the app’s UI components. Swift classes may contain variable properties and constant properties. Variable properties are read/write and are declared with the var keyword. Constant properties, which cannot be modified after they’re initialized, are read-only and are declared with let. These keywords can also be used to declare local and global variables and constants. A variable property defines a getter and a setter that allow you to obtain and modify a property’s value, respectively. A constant property defines only a getter for obtaining its value.

@IBOutlet Properties

Each property for programmatically interacting with a UI component is prefixed with @IBOutlet. This tells Interface Builder that the property is an outlet. You’ll use Interface Builder to connect a UI control to its corresponding outlet in the view controller using drag-and-drop techniques. Once connected, the view controller can manipulate the corresponding UI component programmatically. @IBOutlet properties are variable properties so they can be modified to refer to the UI controls when the storyboard creates them.

Action Methods

When you interact with a UI component (e.g., touching a Slider or entering text in a Text Field), a user-interface event occurs. The view controller handles the event with an action—an event-handling method that specifies what to do when the event occurs. Each action is annotated with @IBAction in your view controller’s class. @IBAction indicates to Interface Builder that a method can respond to user interactions with UI components. You’ll use Interface Builder to visually connect an action to a specific user-interface event using drag-and-drop techniques.

3.2.7 Performing Tasks After a View Loads

When a user launches the Tip Calculator:

  • Its main storyboard is loaded.
  • The UI components are created.
  • An object of the app’s initial view controller class is instantiated.
  • Using information stored in the storyboard, the view controller’s @IBOutlets and @IBActions are connected to the appropriate UI components.

In this app, we have only one view-controller, because the app has only one scene. After all of the storyboard’s objects are created, iOS calls the view controller’s viewDidLoad method—here you perform view-specific tasks that can execute only after the scene’s UI components exits. For example, in this app, you’ll call the method becomeFirstResponder on the UITextField to make it the active component—as if the user touched it. You’ll configure the UITextField such that when it’s the active component, the numeric keypad is displayed in the screen’s lower half. Calling becomeFirstResponder from viewDidLoad causes iOS to display the keypad immediately after the view loads. (Keypads are not displayed if a Bluetooth keyboard is connected to the device.) Calling this method also indicates that the UITextField is the first responder—the first component that will receive notification when an event occurs. iOS’s responder chain defines the order in which components are notified that an event occurred. For the complete responder chain details, visit:

http://bit.ly/iOSResponderChain

3.2.8 Financial Calculations with NSDecimalNumber

Financial calculations performed with Swift’s Float and Double numeric types tend to be inaccurate due to rounding errors. For precise floating-point calculations, you should instead use objects of the Foundation framework class NSDecimalNumber. This class provides various methods for creating NSDecimalNumber objects and for performing arithmetic calculations with them. This app uses the class’s methods to perform division, multiplication and addition.

Swift Numeric Types

Though this app’s calculations use only NSDecimalNumbers, Swift has its own numeric types, which are defined in the Swift Standard Library. Figure 3.3 shows Swift’s numeric and boolean types—each type name begins with a capital letter. For the integer types, each type’s minimum and maximum values can be determined with its min and max properties—for example, Int.min and Int.max for type Int.

Fig. 3.3

Fig. 3.3 | Swift numeric and boolean types.

Swift also supports standard arithmetic operators for use with the numeric types in Fig. 3.3. The standard arithmetic operators are shown in Fig. 3.4.

Fig. 3.4

Fig. 3.4 | Arithmetic operators in Swift.

3.2.9 Formatting Numbers as Locale-Specific Currency and Percentage Strings

You’ll use Foundation framework class NSNumberFormatter’s localizedStringFromNumber method to create locale-specific currency and percentage strings—an important part of internationalization. You could also add accessibility strings and internationalize the app using the techniques you learned in Sections 2.7–2.8.

3.2.10 Bridging Between Swift and Objective-C Types

You’ll often pass Swift objects into methods of classes written in Objective-C, such as those in the Cocoa Touch classes. Swift’s numeric types and its String, Array and Dictionary types can all be used in contexts where their Objective-C equivalents are expected. Similarly, the Objective-C equivalents (NSString, NSArray, NSMutableArray, NSDictionary and NSMutableDictionary), when returned to your Swift code, are automatically treated as their Swift counterparts. In this app, for example, you’ll use class NSNumberFormatter to create locale-specific currency and percentage strings. These are returned from NSNumberFormatter’s methods as NSString objects, but are automatically treated by Swift as objects of Swift’s type String. This mechanism—known as bridging—is transparent to you. In fact, when you look at the Swift version of the Cocoa Touch documentation online or in Xcode, you’ll see the Swift types, not the Objective-C types for cases in which this bridging occurs.

3.2.11 Swift Operator Overloading

Swift allows operator overloading—you can define your own operators for use with existing types. In Section 3.6.7, we’ll define overloaded addition, multiplication and division operators to simplify the NSDecimalNumber arithmetic performed throughout the app’s logic. As you’ll see, you define an overloaded operator by creating a Swift function, but with an operator symbol as its name and a parameter list containing parameters that represent each operand. So, for example, you’d provide two parameters for an overloaded-operator function that defines an addition (+) binary operator—one for each operand.

3.2.12 Variable Initialization and Swift Optional Types

In Swift, every constant and variable you create (including a class’s properties) must be initialized (or for variables, assigned to) before it’s used in the code; otherwise, a compilation error occurs. A problem with this requirement occurs when you create @IBOutlet properties in a view controller using Interface Builder’s drag-and-drop techniques. Such properties refer to objects that are not created in your code. Rather, they’re created by the storyboard when the app executes, then the storyboard connects them to the view controller—that is, the storyboard assigns each UI component object to the appropriate property so that you can programmatically interact with that component.

For scenarios like this in which a variable receives its value at runtime, Swift provides optional types that can indicate the presence or absence of a value. A variable of an optional type can be initialized with the value nil, which indicates the absence of a value.

When you create an @IBOutlet with Interface Builder, it declares the property as an implicitly unwrapped optional type by following the type name with an exclamation point (!). Properties of such types are initialized by default to nil. Such properties must be declared as variables (with var) so that they can eventually be assigned actual values of the specified type. Using optionals like this enables your code to compile because the @IBOutlet properties are, in fact, initialized—just not to the values they’ll have at runtime.

As you’ll see in later chapters, Swift has various language features for testing whether an optional has a value and, if so, unwrapping the value so that you can use it—known as explicit unwrapping. With implicitly unwrapped optionals (like the @IBOutlet properties), you can simply assume that they’re initialized and use them in your code. If an implicitly unwrapped optional is nil when you use it, a runtime error occurs. Also, an optional can be set to nil at any time to indicate that it no longer contains a value.

3.2.13 Value Types vs. Reference Types

Swift’s types are either value types or reference types. Swift’s numeric types, Bool type and String type are all values types.

Value Types

A value-type constant’s or variable’s value is copied when it’s passed to or returned from a function or method, when it’s assigned to another variable or when it’s used to initialize a constant. Note that Swift’s Strings are value types—in most other object-oriented languages (including Objective-C), Strings are reference types. Swift enables you to define your own value types as structs and enums (which we discuss in later chapters). Swift’s numeric types and String type are defined as structs. An enum is often used to define sets of named constants, but in Swift it’s much more powerful than in most C-based languages.

Reference Types

You’ll define a class and use several existing classes in this chapter. All class types (defined with the keyword class) are reference types—all other Swift types are value types. A constant or variable of a reference type (often called a reference) is said to refer to an object. Conceptually this means that the constant or variable stores the object’s location. Unlike Objective-C, C and C++, that location is not the actual memory address of the object, rather it’s a handle that enables you to locate the object so you can interact with it.

Both structs and enums in Swift provide many of the same capabilities as classes. In many contexts where you’d use classes in other languages, Swift idiom prefers structs or enums. We’ll say more about this later in the book.

Reference-Type Objects That Are Assigned to Constants Are Not Constant Objects

Initializing a constant (declared with let) with a reference-type object simply means that the constant always refers to the same object. You can still use a reference-type constant to access read/write properties and to call methods that modify the referenced object.

Assigning References

Reference-type objects are not copied. If you assign a reference-type variable to another variable or use it to initialize a constant, then both refer to the same object in memory.

Comparative Operators for Value Types

Conditions can be formed by using the comparative operators (==, !=, >, <, >= and <=) summarized in Fig. 3.5. These operators all have the same level of precedence and do not have associativity in Swift.

Fig. 3.5

Fig. 3.5 | Comparative operators for value types.

Comparative Operators for Reference Types

One key difference between value types and reference types is comparing for equality and inequality. Only value-type constants and variables can be compared with the == (is equal to) and != (is not equal to) operators. In addition to the operators in Fig. 3.5, Swift also provides the === (identical to) and !== (not identical to) operators for comparing reference-type constants and variables to determine whether they refer to the same object.

3.2.14 Code Completion in the Source-Code Editor

As you type code in the source-code editor, Xcode displays code-completion suggestions (Fig. 3.6) for class names, method names, property names, and more. It provides one suggestion inline in the code (in gray) and below it displays a list of other suggestions (with the current inline one highlighted in blue). You can press Enter to select the highlighted suggestion or you can click an item from the displayed list to choose it. You can press the Esc key to close the suggestion list and press it again to reopen the list.

Fig. 3.6

Fig. 3.6 | Code-completion suggestions in Xcode.

  • + Share This
  • 🔖 Save To Your Account