Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

This chapter is from the book

3.2 Account Class

We present and discuss the Account class’s code in Figs. 3.1–3.5. In Section 3.3, we present a simple program that creates and uses Account objects to demonstrate Account’s capabilities. The project for this example has two Swift files—Account.swift contains Account’s definition and main.swift (Section 3.3) contains the app that uses class Account. We could have defined class Account in main.swift as well, but classes are generally defined in their own files to make the code easier to reuse and maintain. To add a new Swift file to your project, select File > New > File..., then select Swift File from the Source category.

To run the final project, click the Run button (run.jpg) on the Xcode toolbar or press cmd.jpg + R. The results will be displayed in the Debug area at the bottom of the Xcode window (as you saw in Fig. 1.9).

3.2.1 Defining a Class

Line 4 (Fig. 3.1) begins a class definition for class Account. The class keyword introduces a class definition and is immediately followed by the class name (Account).

Fig. 3.1 | Account class definition.

1   // fig03-01-11: Account.swift
2   // Account class with name and balance properties,
3   // an initializer and deposit and withdraw methods
4   public class Account {

Class Names Are Identifiers

Class names are identifiers that use the camel-case naming scheme we discussed in Chapter 2, but, by convention, class names begin with an initial uppercase letter.

Class Body

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

Access Modifiers public, internal and private

Class Account’s definition begins with the keyword public (line 4), which is one of Swift’s three access modifiers (public, internal and private). A class that’s declared public can be reused in other apps—for example, the features in the Swift Standard Library are declared public so that you can use them in your apps. A class that’s declared internal can be used only by other code in the same projectinternal is the default access specifier if you do not provide one. A class that’s declared private can be used only in the file in which its defined. Though we do not reuse class Account outside this chapter’s example, we chose to declare it public so that it can potentially be reused.

3.2.2 Defining a Class Attribute as a Stored Property

Different accounts typically have different names and balances. For this reason, class Account contains a name property (Fig. 3.2) and a balance property (Fig. 3.3). Figure 3.2 defines the stored property name—such properties enable you to store and retrieve values in an object of a class. Each object has its own copy of the class’s stored properties. Swift stored properties are similar to C# properties and to instance variables with corresponding set and get methods in Java and C++.

Fig. 3.2 | Account class stored property name.

5       public var name: String = "" // properties must be initialized
6

Accessing a Stored Property

A class’s properties are defined like other constants and variables, but inside the class’s body. The property in Fig. 3.2 is a variable (var) stored property of type String that’s initialized with an empty String. A variable property is read/write—it allows you to get the property’s value from an object of the class and store a value in an object of the class.

You use an object’s identifier and a dot (.)—known as dot syntax—to access a property. Consider an Account object named account1. In the statement:

account1.name = "Jane Green" // uses the setter to set the name

the expression account1.name uses the property’s setter to store the String "Jane Green" in the account1 object. In the statement:

println(account1.name) // uses the getter to get the name

the expression account1.name uses the property’s getter to retrieve the String "Jane Green" from the account1 object so that it can be displayed with println.

You may also define constant properties in a class with let. A constant property is read only—it provides only a getter for retrieving the value and is used for a value that does not change after it’s initialized.

A Class’s public Properties May Be Accessed Throughout the Class and by Clients of the Class

The name property is defined as public (line 5). A class’s public properties (and other public members) are publicly accessible. They can be accessed throughout the class’s definition and by any code that uses objects of the class—the class’s so-called client code (like main.swift, which you’ll see in Section 3.3). A class’s internal members can be accessed via an object of the class anywhere in the app in which the class is defined. A class’s private members can be used only in the file that defines the class.

Computed Properties

Swift also provides computed properties that do not store data—rather, they manipulate other properties. For example, a Circle class could have a stored property radius and computed properties diameter, circumference and area that would calculate the diameter, circumference and area, respectively, using the stored property radius in the calculations. We’ll define a computed property in Section 6.9.1 and discuss them in more detail in Chapter 8.

3.2.3 Defining a public Stored Property with a private Setter

As you saw in Section 3.2.2, a variable property has a getter and a setter. If a variable property is public, the client code can use the getter to get the property’s value and the setter to modify its value. Though the client code should be able to check the balance, the balance should be modifiable only within class Account, so we can ensure the client code does not modify the balance incorrectly. For this scenario, you can declare that the property’s setter is private. Line 8 (Fig. 3.3) defines the public variable stored property named balance of type Double and initializes it with the value 0.0. The notation private(set) between the public and var keywords indicates that balance’s setter is private and thus can be used only by code in the same file as class Account.

Fig. 3.3 | Account class stored properties.

7      // balance is public, but its setter can be used only in class Account
8      public private(set) var balance: Double = 0.0
9

3.2.4 Initializing a Class’s Properties with init

Swift does not provide default values for a class’s properties—you must initialize them before they’re used. Lines 5 and 8 (Figs. 3.2–3.3) specify default values for both of Account’s properties. But what if you want to provide different values for the name and balance when you create an Account object? Each class you define can optionally provide an initializer with parameters that can be used to initialize a new object of a class. In fact, Swift requires an initializer call for every object that’s created, so this is the ideal point to initialize an object’s properties. For a class that does not explicitly define any initializers, the compiler defines a default initializer (with no parameters) that initializes the class’s properties to the default values specified in their definitions. Initializers are like constructors in most other object-oriented programming languages.

Initializer Definition

Lines 11–19 (Fig. 3.4) define class Account’s public initializer—only the public class members are accessible when the class is reused outside the project in which it’s defined. Each initializer’s name is the keyword init, which is followed by a parameter list enclosed in required parentheses, then the initializer’s body enclosed in braces ({ and }). The parameter list optionally contains a comma-separated list of parameters with type annotations. The argument values passed to the initializer’s parameters initialize the properties for a particular object of the class. As you’ll see in Chapter 8, classes can have multiple initializers—this is called overloading and enables objects of a class to be initialized in different ways. The initializer for class Account provides a name parameter of type String and a balance parameter of type Double, representing the account holder’s name and starting balance, respectively.

Fig. 3.4 | Account class initializer.

10     // initializer
11     public init(name: String, balance: Double) {
12         self.name = name
13
14         // validate that balance is greater than 0.0; if not,
15         // property balance keeps its initial value of 0.0
16         if balance > 0.0 {
17             self.balance = balance
18         }
19     }
20

Each parameter must be declared with a type annotation specifying the type of the expected argument. When you create a new Account object (as you’ll see in Section 3.3), you’ll pass as arguments the account holder’s name (a String) and starting balance (a Double)—the initializer will receive those values in the parameters name and balance, respectively. The initializer assigns the parameter name to the property name (line 12) and validates the parameter balance, assigning it to the property balance (line 17) only if the corresponding argument is greater than 0.0—otherwise, property balance retains its default value of 0.0 that was specified in its definition (line 8 of Fig. 3.3).

Parameters Are Local to Their Defining Initializer, Method or Function

Parameters are local to the initializer, method or function in which they’re defined, as are any variables and constants defined in the body of an initializer, method or function. If a local variable or constant has the same name as a property, using the variable or constant in the body refers to the local variable or constant rather than the property—the local identifier shadows the property. You use the keyword self (like this in other popular object-oriented languages) to refer to the shadowed property explicitly, as shown on the left side of the assignments in lines 12 and 17 (Fig. 3.4).

There’s No Default Initializer in a Class That Defines an Initializer

If you define an initializer for a class, the compiler will not create a default initializer for that class. In that case, you will not be able to create an Account object with the expression Account()—unless the custom initializer you define takes no parameters.

3.2.5 Defining a Class’s Behaviors as Methods

Class Account defines two public methods (Fig. 3.5) for manipulating the balance:

  • Method deposit (lines 22–27) ensures that the deposit amount is positive and, if so, adds the amount to the balance.
  • Method withdraw (lines 30–38) ensures that the withdrawal amount is positive and that subtracting that amount from the balance will not overdraw the account, and, if so, subtracts the amount from the balance.

Fig. 3.5 | Account class methods deposit and withdraw.

21     // deposit (add) a valid amount into the Account,
22     public func deposit(amount: Double) {
23         // if amount is valid, add it to the balance
24         if amount > 0.0 {
25             balance = balance + amount
26         }
27     }
28
29         // withdraw (subtract) a valid amount from the Account
30         public func withdraw(amount: Double) {
31             // if amount is valid, and the balance will not
32             // become negative, subtract it from the balance
33             if amount > 0.0 {
34                 if balance - amount >= 0.0 {
35                     balance = balance - amount
36                 }
37             }
38         }
39    }

Defining a Method

A method definition begins with the keyword func (lines 22 and 30) followed by the method’s name and parameter list enclosed in required parentheses, then the method’s body enclosed in braces ({ and }). Like an initializer, the parameter list optionally contains a comma-separated list of parameters with type annotations. Methods deposit and withdraw each receive one parameter of type Double representing the amount to deposit or withdraw, respectively.

Return Type of a Method

A method may also specify a return type by following the parameter list with -> and the type of the value the method returns. A method that does not specify a return type does not return a value, as is the case for methods deposit and withdraw in class Account. Methods with return values use return statements to pass results back to their callers. As you’ll see, Swift methods and functions can return more than one value at a time via a tuple, which you’ll learn about in Chapter 5.

Initializers Cannot Return Values

An important difference between initializers and methods is that initializers cannot return values, so they cannot specify a return type.

A Method Defined Outside a Type Definition Is a Function

If a method is defined outside a class (or struct or enum), then it’s a function (sometimes called a free function or global function)—println and print are two of the many functions defined in the Swift Standard Library. We define a function in Section 3.3.3.

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