Home > Articles > Programming > General Programming/Other Languages

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

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

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   }

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) 
20   // display initial balance of each Account
21   println(formatAccountString(account1))
22   println(formatAccountString(account2))
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
27   println("\ndepositing " + formatter.stringFromNumber(depositAmount) +
28       " into account1\n")
29   account1.deposit(depositAmount)
31   println(formatAccountString(account1))
32   println(formatAccountString(account2))
34   depositAmount = 123.45
35   println("\ndepositing " + formatter.stringFromNumber(depositAmount) +
36       " into account2\n")
37   account2.deposit(depositAmount)
39   println(formatAccountString(account1))
40   println(formatAccountString(account2))
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
45   println("\nwithdrawing " + formatter.stringFromNumber(withdrawalAmount) +
46       " from account1\n")
47   account1.withdraw(withdrawalAmount)
49   println(formatAccountString(account1))
50   println(formatAccountString(account2))
52   withdrawalAmount = 100.00
53   println("\nwithdrawing " + formatter.stringFromNumber(withdrawalAmount) +
54       " from account2\n")
55   account2.withdraw(withdrawalAmount)
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

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.


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.


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.


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.


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


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


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.


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.


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