Introduction to Classes, Objects, Methods and Functions in Swift
In Chapter 2, you worked with built-in Swift types (Int and String) and functions (print and println). Throughout the book, you’ll use many more preexisting Swift types and functions, as well as capabilities of the Cocoa and Cocoa Touch libraries. In this chapter, you’ll create your own types in the form of classes. Each new class you create becomes a new type that can be used to define variables and create objects. In later chapters, you’ll also create new struct and enum types.
In this chapter, we create and use a simple bank-account class—Account. This class maintains as attributes the account holder’s name and balance, and provides behaviors for querying the balance, making deposits (which increase the balance) and making withdrawals (which decrease the balance). We also discuss the differences between value types and reference types.
In Chapter 2 we used the data type Int to represent integers. In this chapter, we use data type Double to represent an Account’s balance as a number that can contain a decimal point—such numbers are called floating-point numbers (e.g., 43.95 or –129.8873).
Swift provides two built-in types for storing floating-point numbers in memory—Float and Double. Variables of type Float represent single-precision floating-point numbers and might have as few as six significant digits. Variables of type Double represent double-precision floating-point numbers. These require twice as much memory as Float variables and have a minimum of 15 significant digits.
Most programmers represent floating-point numbers with type Double. In fact, Swift treats all floating-point literals you type in a program’s source code (such as 7.33 and 0.0975) as Double values by default.
In later chapters, we’ll represent monetary amounts precisely with the Cocoa and Cocoa Touch Foundation framework class NSDecimalNumber—as you should do when writing business-critical applications that process monetary amounts. We demonstrate NSDecimalNumber in Section 8.10.