Home > Articles > Programming > General Programming/Other Languages

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

This chapter is from the book

3.3 Creating and Using Account Objects

Next, we present main.swift, which demonstrates class Account’s capabilities. We present the code in Figs. 3.6–3.11 and, as appropriate, show the output produced by the statements in each figure.

3.3.1 Importing the Foundation Framework

A great strength of the iOS 8 and OS X Yosemite platforms is their rich set of predefined capabilities that you can reuse rather than “reinventing the wheel.” These capabilities are grouped into frameworks. To use features from the iOS 8 and OS X Yosemite frameworks, you must import them into your Swift code. Throughout this app, we display an Account’s balance in a locale-specific currency format. To do so, we use an object of the Foundation framework’s NSNumberFormatter class. In Fig. 3.6, line 4 is an import declaration indicating that the program uses predefined capabilities from the Foundation framework. All import declarations must appear before any other Swift code (except comments) in your source-code files.

Fig. 3.6 | Importing a framework for use in Swift code.

1   // fig03-01-11: main.swift
2   // Using class Account's init method to initialize an Account's
3   // name property when the Account object is created
4   import Foundation // use Cocoa/Cocoa Touch Foundation Framework
5

3.3.2 Creating and Configuring an NSNumberFormatter to Format Currency Values

Line 7 (Fig. 3.7) creates an NSNumberFormatter object. Unlike many other object-oriented programming languages, Swift does not have a new operator for creating an object. Instead, you simply follow the class name with parentheses. Arguments, if any, for initializing the object’s properties are specified as a comma-separated list inside the parentheses. Line 8 uses the dot (.) syntax to access and set the NSNumberFormatter object’s numberStyle property to the enum constant NSNumberFormatterStyle.CurrencyStyle, indicating that the formatter object produces locale-specific currency Strings (we’ll say more about enums in later chapters).

Fig. 3.7 | Creating and configuring an NSNumberFormatter object.

6   // create and configure an NSNumberFormatter for currency values
7   var formatter = NSNumberFormatter()
8   formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
9

Xcode Quick Help Inspector

When you place the cursor in your source code (either in a playground or in the Editor area of a project), you can use the Quick Help inspector to get context-sensitive help—documentation that’s based on the cursor position in the source code. For example, clicking in a class name shows a description of the class, and clicking in a property name shows a description of the property. The Quick Help inspector also provides links to more detailed documentation that often shows code snippets in both Swift and Objective-C, so you can see how the selected item is used in each language. You can view the Quick Help inspector in Xcode’s Utilities area or by selecting View > Utilities > Show Quick Help Inspector. You can also hold the option key and click an item to view pop-up quick help for that item.

Jump to Definition Option in the Xcode Editor

In an Xcode project, you can hold the control key and click an item in your source code, then select Jump To Definition to jump to that item’s definition. For Swift Standard Library types and functions, this displays a file containing their declarations and explanatory comments.

3.3.3 Defining a Function—formatAccountString

Figure 3.8 defines a function formatAccountString, which we use throughout main.swift to create a formatted String representation of an Account’s name and balance. In main.swift, statements that are defined outside any function execute in sequence when the program begins execution. Statements in a function, however, execute only when that function is called.

Fig. 3.8 | Function to display an Account’s information.

10   // function to return String representation of an Account's information
11   func formatAccountString(account: Account) -> String {
12       return account.name + "'s balance: " +
13           formatter.stringFromNumber(account.balance)!
14   }
15

Function formatAccountString receives an Account object and returns a String (specified by the return type in line 11) containing the name and balance property values in the Account object. Line 13 uses the formatter object’s stringFromNumber method to get a locale-specific, currency-formatted string representing the balance. We use the + operator in lines 12 and 13 to concatenate the name String, the literal "'s balance: " and the String returned by stringFromNumber.

The return statement passes the concatenated String back to the caller. For example, when the value is returned to the println statement in line 21 of Fig. 3.9, the statement displays the returned String.

Fig. 3.9 | Creating and manipulating an Account object.

16   // create two Account objects
17   let account1 = Account(name: "Jane Green", balance: 50.00)
18   let account2 = Account(name: "John Blue", balance: -7.53) 
19
20   // display initial balance of each Account
21   println(formatAccountString(account1))
22   println(formatAccountString(account2))
23
Jane Green's balance: $50.00
John Blue's balance: $0.00

It’s possible that stringFromNumber will be unable to produce a formatted String. For cases in which a method might sometimes—but not always—return a value, Swift allows a method to return an optional, which is either a value of the specified type or nil to indicate the absence of a value (similar to null or NULL in some programming languages). An optional is indicated by following a type with a ?stringFromNumber’s return type is actually String? (an optional String). The exclamation point (!) at the end of line 13 tells Swift to assume that the optional String returned by stringFromNumber contains an actual String value (not nil) and so lines 12–13 can return that value. Note, however, that if the optional String contains nil, a runtime error will occur and the program will stop executing. We discuss optionals and how to check them for nil beginning in Section 6.9.5.

3.3.4 Creating Objects and Calling an Initializer

Lines 17–18 (Fig. 3.9) create and initialize two Account objects and assign them to account1 and account2. When you implicitly invoke a class’s initializer, you must specify each parameter’s name and a colon (:) before the corresponding argument value, as in lines 17–18). Lines 21–22 display the results of calling function formatAccountString to get String representations of the Account objects’ contents after they’re initialized—the corresponding output is shown below Fig. 3.9.

3.3.5 Calling Methods on Objects—Depositing into Account Objects

Figure 3.10 demonstrates depositing into each Account (lines 29 and 37) to show that each Account maintains its own copy of the balance property. When calling a method, if it has only one parameter, you simply pass the argument value in the parentheses of the method call. If a method has more than one parameter, each argument after the first must be preceded by the parameter’s name and a colon (:)—we discuss the reasoning for this in Section 5.9. After each deposit, we display both Account objects to emphasize that only one Account object’s balance is modified by each call to deposit.

Fig. 3.10 | Depositing into Account objects.

24   // test Account's deposit method
25   var depositAmount = 25.53
26
27   println("\ndepositing " + formatter.stringFromNumber(depositAmount) +
28       " into account1\n")
29   account1.deposit(depositAmount)
30
31   println(formatAccountString(account1))
32   println(formatAccountString(account2))
33
34   depositAmount = 123.45
35   println("\ndepositing " + formatter.stringFromNumber(depositAmount) +
36       " into account2\n")
37   account2.deposit(depositAmount)
38
39   println(formatAccountString(account1))
40   println(formatAccountString(account2))
41
depositing $25.53 into account1

Jane Green's balance: $75.53
John Blue's balance: $0.00

depositing $123.45 into account2

Jane Green's balance: $75.53
John Blue's balance: $123.45

3.3.6 Calling Methods on Objects—Withdrawing from Account Objects

Figure 3.11 demonstrates withdrawing from each Account (lines 47 and 55). Once again, like deposit, method withdraw has only one parameter, so you simply pass the argument value in the parentheses of the method call. After each withdrawal, we display both Account objects.

Fig. 3.11 | Withdrawing from Account objects.

42   // test Account's withdraw method
43   var withdrawalAmount = 14.27
44
45   println("\nwithdrawing " + formatter.stringFromNumber(withdrawalAmount) +
46       " from account1\n")
47   account1.withdraw(withdrawalAmount)
48
49   println(formatAccountString(account1))
50   println(formatAccountString(account2))
51
52   withdrawalAmount = 100.00
53   println("\nwithdrawing " + formatter.stringFromNumber(withdrawalAmount) +
54       " from account2\n")
55   account2.withdraw(withdrawalAmount)
56
57   println(formatAccountString(account1))
58   println(formatAccountString(account2))
withdrawing $14.27 from account1

Jane Green's balance: $61.26
John Blue's balance: $123.45

withdrawing $100.00 from account2

Jane Green's balance: $61.26
John Blue's balance: $23.45
  • + Share This
  • 🔖 Save To Your Account