Home > Articles > Programming > General Programming/Other Languages

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020