Chapter    5

Learning Swift

To write any program, you need to choose a programming language. A programming language lets you define commands for the computer to follow. There’s no one “best” programming language because every programming language is meant to solve a specific problem. That means that a programming language may be great at solving certain types of problems, but horrible at solving other types of programs.

With most programming languages, there’s a tradeoff between ease of use and efficiency. For example, the BASIC programming language is meant to be easy to learn and use while the C programming language is meant to give you complete control over the computer. By maximizing computer efficiency, the C language is great for creating complicated programs such as operating systems or hard disk utility programs.

Since BASIC was never designed for maximum control over a computer, BASIC would never be used to create an operating system or a hard disk utility program. Since C was designed for maximum computer efficiency, it’s difficult for novices to learn and even difficult for experienced programmers to use. The majority of errors or bugs in many programs are due solely to the complexity of the C programming language that confounds even professional programmers with decades of experience.

In the world of Xcode, Apple’s official programming language used to be Objective-C, which was a superset of the C programming language and an alternative to the object-oriented C++ language. Unfortunately, Objective-C can still be difficult to learn and even harder to master. By making programming harder than it needs to be, Objective-C makes creating OS X and iOS software difficult for novices and experienced programmers alike.

That’s why in 2014, Apple introduced a new programming language called Swift. Swift is meant to be just as powerful as Objective-C while also being much easier to learn. Because Apple will use Swift for both OS X and iOS programming, Swift is now the future programming language for the Macintosh, iPhone, iPad, Apple Watch, Apple TV, CarPlay, and any other future products from Apple.

Since so many people have written programs using Objective-C, there will always be a need for programmers to modify existing Objective-C programs. However, you can always mix Objective-C and Swift in a program. That means over time, there will be less of a need for Objective-C programmers and more of a need for Swift programmers. If you want to learn the most powerful programming language for writing OS X and iOS programs, you want to learn Swift.

 Note  If you’re already familiar with Objective-C, you’ll notice several ways that Swift makes coding far easier. First, Swift doesn’t require a semicolon to end each line. Second, Swift doesn’t need asterisks to represent pointers or square brackets to represent method calls to objects. Third, Swift stores everything in a single .swift file in comparison to Objective-C that needs to create an .h header file and an .m implementation file. If you know nothing about Objective-C, just look at any program written in Objective-C and see how confusing the code can be. One look at Objective-C code will make you realize how much easier learning and using Swift can be.

Using Playgrounds

In the old days, programmers had two types of tools to help them learn programming. The first is called an interpreter. An interpreter let you type in a command and then would immediately show you the results. That way you could see exactly what you were doing right or wrong.

The drawback with interpreters was that they were slow and that you couldn’t use them to create programs you could sell. To run a program in an interpreter, you needed both the interpreter and the file (called the source code) that contained all your commands written in a particular programming language. Because you had to give away your source code to run programs in an interpreter, others could easily copy your program and steal it. As a result, interpreters were only useful for learning a language but weren’t practical for selling software.

The second tool that programmers use to learn programming is called a compiler. A compiler takes a list of commands, stored in a file, and converts them to machine language so the computer can understand them. The advantage of a compiler is that it keeps others from seeing the source code of your program.

The problem with using a compiler is that you have to write a complete program and compile it just to see if your commands work or not. If your commands don’t work, now you have to go back and fix the problem. Unlike the interactive nature of an interpreter, a compiler makes learning a programming language much slower and clumsier.

With an interpreter you could write a command and immediately see if it worked or not. With a compiler, you had to write a command, compile your program, and run your program to see if it worked or not.

Interpreters are better for learning while compilers are better for creating software you can distribute to others without giving away your source code. Fortunately, Xcode gives you the best of both worlds.

When you run your program, you’re using Xcode’s compiler. However, if you only want to experiment with some commands, you can use Xcode’s interpreter called a Playground.

Playgrounds let you experiment with Swift code to see if it works or not. When you get it to work, then you can copy and paste it into your project files and compile them to create a working program. By giving you the ability to use both an interpreter and a compiler, Xcode makes it easy to learn Swift and practical for creating programs you can sell or give away to others.

To create a playground, follow these steps:

  1. Start Xcode.
  2. Choose File image New image Playground. (If you see the Xcode welcome screen, you can also click on Get started with a playground.) Xcode asks for a playground name and platform as shown in Figure 5-1.

    9781484212349_Fig05-01.jpg

    Figure 5-1. Creating a playground file

  3. Click in the Name text field and type IntroductoryPlayground.
  4. Click in the Platform pop-up menu and choose OS X. Xcode asks where you want to save your playground file.
  5. Click on a folder where you want to save your playground file and click the Create button. Xcode displays the playground file as shown in Figure 5-2.

    9781484212349_Fig05-02.jpg

    Figure 5-2. The playground window

  6. Edit the second line as follows:
    var str = "This is the Swift interpreter"

Notice that the playground window immediately displays the results of your code change in the right margin as shown in Figure 5-3.

9781484212349_Fig05-03.jpg

Figure 5-3. The playground window displays code changes immediately

Playgrounds let you freely experiment with Swift and access every class in the Cocoa framework without worrying about getting your Swift code to work with a user interface.

Creating Comments in Swift

The simplest commands to type in any programming language are comments. A comment is any text that exists solely for humans to read. In the top of the Playground file, you can see a comment that appears in green that reads:

// Playground – noun: a place where people can play

Comments let you leave notes about code such as the name of the person who wrote it, the date it was last modified, a description of what the code does and what other files it may depend on, or anything else you think might be useful for you (or another programmer) to read in the future.

If you just need to write a comment on a single line, you can use the // symbols. Anything that appears to the right of the // symbols are comments that the computer completely ignores. Xcode helps identify comments by displaying text in green.

If you need to write a command that spans two or more lines, you can type multiple // symbols in front of each line, but another solution is to define the beginning of a comment with the /* symbols and define the ending of that comment with the */ symbols such as:

/* This is a comment that
spans multiple lines */

Comments exist for your benefit so feel free to use them whenever you need to write and store crucial information about your code.

 Note  One popular use for comments is to temporarily disable Swift code without having to erase it. By disabling one or more lines of Swift code by turning them into a comment, you can see how your program runs as if any commented lines of code were deleted. When you’re done testing, you can remove the comment symbols and put your code back in your program without retyping it all over again.

Storing Data in Swift

Every program needs to accept data, manipulate that data somehow, and display that result to the user. To accept data, programs need to store data temporarily in memory. Technically, computers store data in memory addresses, which can be confusing to remember. To make it easier to know where data gets stored, programming languages let you give those memory addresses descriptive names. In Swift, those two choices are called:

  • Variables
  • Constants

The idea behind both variables and constants is that you define a descriptive name and assign it to hold data such as:

str = "This is the Swift interpreter"

In the above example, “str” is the descriptive name, and “This is the Swift interpreter” is the data that gets stored. Data can either be a text string or a number such as an integer (3, 12, -9, etc.) or a decimal also known as a floating-point number (12.84, -0.83, 8.02, etc.). At any given time, you can store one chunk of data in a descriptive name, which can be defined as a variable or a constant.

The main difference between a variable and a constant is that you can reuse a variable by storing new data as many times as you want (hence the name “variable”). A constant only lets you store data in it once.

To define a variable, you have to use the “var” keyword like this:

var str = "This is the Swift interpreter"

To define a constant, you have to use the “let” keyword like this:

let str = "This is the Swift interpreter"

The first time you store data in a variable or a constant, Swift infers the data type such as:

  • Text strings (defined as String)
  • Integers (defined as Int)
  • Decimal numbers (defined by Float and Double)

Knowing the data type a variable or constant can hold is crucial because it can only hold one type of data and nothing else. So if you create a variable and store a string in it, that variable can only store strings from now on.

 Note  Swift is known as a type-safe programming language because it explicitly defines the type of data each variable or constant can store.

To make it clear what type of data a variable or constant can hold, you can explicitly define the data type such as:

var cat: String
var dog: Int
var fish: Float
var snake: Double

Based on these data type declarations, the “cat” variable can only store strings, the “dog” variable can only store integers, the “fish” variable can only hold floating-point numbers, and the “snake” variable can only hold double-precision floating-point numbers.

If you try to store the wrong type of data in a variable or constant, Swift won’t let you. This is to prevent problems when a program tries to use the wrong type of data. For example, if a program asks the user for how many items to order and the user types in “five” instead of the number 5, the program would have no idea how to do a mathematical calculation on “five,” which would cause the program to either crash or work erratically.

 Note  Both a Float and a Double data type can hold decimal numbers. The difference is that a Double data type can hold more precise decimal numbers that contain additional decimal places along with smaller and larger values. If you just need to use decimal numbers, use Float since it takes less memory than Double. If you need precise accuracy with decimal numbers, use Double. When Swift infers a decimal number, it infers a Double data type.

Swift gives you three ways to define a variable or a constant:

  • let cat = "Oscar" // Infers String data type
  • let cat: String = "Oscar"
  • let cat: String

    cat = "Oscar"

The first method lets you store data directly into a variable or constant. Based on the type of data you first store, Swift infers the data type as String, Int, or Double (not a Float because a Float stores less precise decimal numbers than Double and Swift assumes you want exact precision).

The second method lets you explicitly declare the data type and store data into that variable or constant. While this can be wordier, it’s clear exactly what type of data you want to store.

The third method takes two lines. The first line defines the data type. The second line actually stores the property type of data. This can be handy for variables that may get assigned different data in various parts of your program. You could declare the variable near the top of your file to make it easy to find, then assign data to it later when you need it.

To see how to declare variables and constants in Swift, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded into Xcode.
  2. Modify the Swift code in the playground file as follows:
    import Cocoa

    let cat: String
    cat = "Oscar"

    cat = "Bo"

    Notice that when you try to assign new data to a constant that already holds data, you get an error message. Clicking on that warning icon in the left margin displays an error message as shown in Figure 5-4.

    9781484212349_Fig05-04.jpg

    Figure 5-4. An error message warns that you cannot store data in a constant more than once

     Note  Constants are also called “immutable” because they cannot be changed after you’ve stored data in them. Variables are called “mutable” because you can constantly change the data that they store. Just remember that variables can only hold one chunk of data at a time. The moment you store new data in a variable, any existing data in that variable gets wiped out.

  3. Modify the Swift code in the playground file by changing the constant to a variable (replacing “let” with “var”) as follows:
    import Cocoa

    var cat: String
    cat = "Oscar"

    cat = 42.7

    Notice that when you try to assign a number to a variable that can only hold strings, you get a warning. Clicking on that warning icon in the left margin displays an error message as shown in Figure 5-5.

    9781484212349_Fig05-05.jpg

    Figure 5-5. An error message warns that you cannot store the wrong type of data

  4. Modify the Swift code in the playground file as follows:
    import Cocoa

    var cat: String
    cat = "Oscar"

    var greeting = "Hello, "
    var period : String = "."

    print (greeting + cat + period)

    Notice that playground displays the results of your Swift code in the right margin as shown in Figure 5-6.

    9781484212349_Fig05-06.jpg

    Figure 5-6. The right margin of the playground window constantly shows the result of your code

Typealiases

Declaring variables as data types such as Int, Double, or String only tells you what type of data it can hold, but it doesn’t tell you the meaning of that data. For example, if you declared two variables as Int data types, each could hold integers but one variable might represent ages and the other variable might represent Employee ID numbers.

To make the purpose of data types clearer, Swift lets you use something called typealiases. A typealias lets you give a descriptive name to a generic data type name such as:

typealias EmployeeID = Int

Now instead of declaring a variable as an integer (Int) data type, you could declare it as an EmployeeID data type such as:

typealias EmployeeID = Int
var employee : EmployeeID
employee = 192

This is equivalent to:

var employee : Int
employee = 192

Using Unicode Characters as Names

In most programming languages, variables and constants are limited to a fixed range of characters, often excluding foreign language characters. To help make Swift more accessible to programmers comfortable with other languages, Swift lets you use Unicode characters for your variable and constant names.

Unicode is a new universal standard that represents different characters. If you choose Edit image Emoji & Symbols, you can choose from a limited number of characters that you can use instead of or in addition to ordinary letters and numbers as shown in Figure 5-7.

9781484212349_Fig05-07.jpg

Figure 5-7. Xcode lets you use special characters as variable or constant names

To see how to use special characters in variable names, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Delete all the code in your playground except for the “import Cocoa” line.
  3. Underneath the “import Cocoa” line, type let and press the spacebar.
  4. Choose Edit image Emoji & Symbols. A pop-up window appears as shown in Figure 5-8.

    9781484212349_Fig05-08.jpg

    Figure 5-8. A pop-up window with different categories of special characters

  5. Click on any character that looks interesting. Xcode types that character as your constant name.
  6. Type = “Funny symbol here” and press Return.
  7. Copy the character and paste it in between the parentheses of the print command. Notice that the right margin of the playground window displays the contents of your constant variable as shown in Figure 5-9.

    9781484212349_Fig05-09.jpg

    Figure 5-9. Using a special character as a constant name in Swift code

Special characters can come in handy for displaying actual mathematical symbols instead of spelling them out, or typing variable or constant names in a foreign language. By making variable and constant names more versatile, Swift makes programming understandable for more people.

Converting Data Types

If you have a number stored as an integer and need to convert it to a decimal, or if you have a decimal and need to convert it to an integer, what can you do? The answer is that you can convert one number data type to another just by specifying the data type you want such as:

Int(decimal)

The Int data type in front tells Swift to convert the number inside the parentheses to an integer. If the number is a decimal, converting it to an integer basically means dropping all numbers after the decimal point, so a number such as 4.9 would be turned into the integer 4.

When Swift converts an integer to a decimal number, it simply tacks on a decimal point with zeroes. So if you converted the integer 75 to a floating-point number, Swift would now store it as 75.0. To see how converting integers to decimals (and vice versa) works, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code in the playground file as follows:
    import Cocoa
    var whole : Int = 4
    var decimal : Double = 4.902

    print (Int(decimal))
    print (Double(whole))

Notice how Swift turns an integer into a decimal (changing 4 to 4.0) and how it turns a decimal into an integer by dropping every value to the right of the decimal point (changing 4.902 to 4) as shown in Figure 5-10.

9781484212349_Fig05-10.jpg

Figure 5-10. Changing integers to decimals and vice versa

Computed Properties

Up until this point, declaring variables and constants, then assigning data to those variable or constants is little different than other programming languages. If you have one variable related to another one, you could do something like this:

var cats = 4
var dogs: Int

dogs = cats + 2

print (dogs)

Unfortunately, this separates the variable declaration for “dogs” from the actual setting of the value of the “dogs” variable. To keep a variable declaration linked with the code that defines it, Swift offers something called computed properties.

With a computed property, you don’t store data directly into a variable. Instead, you define the data type a variable can hold and then use other variables or constants to calculate a new value to store in that variable. This calculation is known as a getter with code that looks like this:

var dogs : Int {
    get {
        return cats + 2 // Code to calculate a value

    }
}

The above code declares a variable called “dogs” that called only hold integer (Int) data types. Then it encloses code in curly brackets known as a getter (defined by the keyword “get”).

You can actually have any amount of Swift code inside the getter’s curly brackets, but this example only includes the most important line, which uses the “return” keyword to return a value that gets stored in the “dogs” variable.

In this case, it takes the value stored in the “cats” variable (which must be defined with a value elsewhere in your program), adds 2 to that value, and stores that new value in the “dogs” variable. Change the code in the getter and you change the computed value that gets stored in the “dogs” variable.

Let’s see how that works by following these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code in the playground file as follows:
    import Cocoa

    var cats = 4

    var dogs : Int {
        get {
            return cats + 2 // Code to calculate a value
        }
    }

    print (dogs)

Notice that the right margin of the playground window shows the value of dogs as shown in Figure 5-11.

9781484212349_Fig05-11.jpg

Figure 5-11. The right margin of the playground window shows how the getter portion works

Getters use code to calculate the value of a variable. A second type of computed property is known as a setter, which runs code that calculates the value of a different variable.

A setter runs every time its variable gets assigned a value. To see how getters and setters work, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code in the playground file as follows:
    import Cocoa

    var cats = 4
    var dogs : Int {
        get {
            return cats + 2 // Code to calculate a value
        }
        set(newValue) {
            cats = 3 * newValue
        }
    }

    print (dogs)
    print (cats)
    dogs = 5
    print (dogs)
    print (cats)

 Note  In the above setter code, “newValue” is actually a default variable that you can omit such as:

set {
  cats = 3 * newValue
}

If you want to define your own variable name (instead of using the default newValue variable), then you must put that new name within the parentheses like this:

set (myOwnVariable){
  cats = 3 * myOwnVariable
}

Notice how the value of the cats and dogs variables change when you assign a different value to the dogs variable as shown in Figure 5-12.

9781484212349_Fig05-12.jpg

Figure 5-12. The right margin of the playground window shows how the getter and setter code works

Let’s go through this code line by line. First, the number 4 gets stored in the “cats” variable. Using the “cats” variable (4) in the getter returns cats + 2 or 4 + 2 (6). So the first print (dogs) command prints 6.

The second print (cats) prints the value of the “cats” variable, which is still 4.

When the “dogs” variable gets assigned the number 5, it runs the setter. The temporary variable “newValue” gets assigned the number 5, which calculates a new value for “cats” as 3 * newValue, which is 3 * 5 or 15. The value of the “cats” variable is now set to 15.

Now the next print (dogs) command runs, using the value of “dogs,” which is calculated by the getter. Since the value of “cats” is 15, the getter calculates cats + 2 or 15 + 2, which is 17. So the next print (dogs) command prints 17 and the last print (cats) command prints 15.

 Note  Computed properties can run code when assigning a value to a variable. However, use computed properties sparingly since they can make your code harder to understand. Computed properties are most often used for class properties in object-oriented programming. For example, if an object represents a square drawn on the screen, changing the width of the square must also change the height of that square at the same time (and vice versa).

Using Optional Variables

The biggest flaw when you declare a variable is that you can’t use that variable until you store data in it. If you try using a variable before it stores any data, your program will fail and crash. To avoid this problem, many programmers initially store “dummy” data in a variable. Unfortunately, such “dummy” data can still be used by a program and cause errors.

To avoid this problem, Swift offers something called optional variables. An optional variable can store data or nothing at all. If an optional variable contains nothing, it’s considered to hold a value called nil. By using optional variables, you avoid crashing a program if a variable doesn’t contain any data.

To create an optional variable, you just declare a variable and its data type with a question mark like this:

var fish : String?

The question mark identifies a variable as an optional. You can use optional variables exactly like ordinary variables to store data in them such as:

fish = "goldfish"

Although storing data in an optional variable is no different than storing data in an ordinary variable, retrieving data from an optional variable requires extra steps. First, you must check if the optional variable even has data in it or not. Once you know that an optional variable contains data, you have to unwrap that optional to get to the actual data by using an exclamation mark such as:

print (fish!)

To see how optional variables work, try the following:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code as follows:
    import Cocoa

    var fish : String?
    fish = "goldfish"
    print (fish)
    print (fish!)

    Notice that “fish” by itself is actually an optional variable, but when you use the exclamation mark to unwrap it, you access the actual data inside the optional as shown in Figure 5-13.

    9781484212349_Fig05-13.jpg

    Figure 5-13. Seeing the difference between an optional and the unwrapped data inside an optional

  3. Type two additional lines of code underneath:
    var str : String
    str = fish

Notice that you can’t assign the optional variable “fish” to “str” because “str” can only hold String data types. Instead, you must unwrap the optional variable “fish” and retrieve its actual string content by using the exclamation mark like this:

var str : String
str = fish!

Before unwrapping optional variables to get to their data, always check to see if the optional variable contains a nil value or a variable. If you try to use an optional variable when it contains a nil value, your program will crash.

To check if an optional variable holds a nil value or not, you have two options. First, you can explicitly check for a nil value like this:

if fish != nil {
    print ("The optional variable is not nil")
}

This code checks if the “fish” optional variable is not equal to (!=) nil. If an optional variable is not nil, then it must hold a value so then it’s safe to retrieve it.

A second way to check if an optional variable has a value or not is to assign it to a constant like this:

if let food = fish {
    print ("The optional variable has a value")
    print (food)
}

If the optional variable has a value, it stores that value in a constant (or another variable). Now you can access that value through the constant or variable. To see how this works, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code as follows:
    import Cocoa
    var fish : String?
    fish = "goldfish"

    if fish != nil {
        print ("The optional variable is not nil")
        var str : String
        str = fish!
        print (str)
    }

    if let food = fish {
        print ("The optional variable has a value")
        print (food)
    }

Notice that you can retrieve the value in an optional variable by unwrapping it with an exclamation mark or storing it in a constant and then using that constant as shown in Figure 5-14.

9781484212349_Fig05-14.jpg

Figure 5-14. Two ways to access a value stored in an optional variable

Linking Swift Code to a User Interface

Every program needs to store data, and one of the most common ways to store data in a variable is to retrieve data from a user interface. To link a user interface item to Swift code, you need to create an IBOutlet variable.

If you had a text field connected to an IBOutlet variable, anything the user typed in the text field would automatically get stored in the IBOutlet variable. Likewise, anything you store in the IBOutlet variable would suddenly appear in the text field. IBOutlet variables act like a link between your Swift code and your user interface as shown in Figure 5-15.

9781484212349_Fig05-15.jpg

Figure 5-15. IBOutlet variables link your user interface items with Swift code

Since user interface items such as text fields may initially be empty, IBOutlet variables are defined as implicitly unwrapped optional variables defined by an exclamation mark like this:

@IBOutlet weak var labelText: NSTextField!

If an IBOutlet were a regular variable and connected to an empty text field, your program would risk crashing without any data in the IBOutlet variable.

If an IBOutlet were an optional variable, you could define it with a question mark like this:

@IBOutlet weak var labelText: NSTextField?

Unfortunately, every time you wanted to access the data stored in this optional variable, you would have to type an exclamation mark. If you accessed this IBOutlet variable multiple times, each time you would have to type an exclamation mark, which can get annoying while making your code look harder to read.

To let you access an IBOutlet variable without typing exclamation marks all the time, it’s easier to create an IBOutlet variable as an implicitly unwrapped optional variable, which means that if it holds a value, you can access it without typing the unwrapping exclamation mark.

To see how Xcode creates IBOutlets as implicitly unwrapped optional variables, open the MyFirstProgram project that you created earlier:

  1. Make sure your MyFirstProgram is loaded in Xcode.
  2. Click on the AppDelegate.swift file in the Project Navigator. Xcode’s middle pane displays the contents of that .swift file. Notice that all the IBOutlet variables are declared with an exclamation mark, meaning they’re implicitly unwrapped optional variables:
    @IBOutlet weak var labelText: NSTextField!
    @IBOutlet weak var messageText: NSTextField!

    Also notice that the IBAction changeCase method lets you access the contents of these implicitly unwrapped optional variables without using an exclamation mark.

    @IBOutlet weak var labelText: NSTextField!
    @IBOutlet weak var messageText: NSTextField!

    @IBAction func changeCase(sender: NSButton) {
        labelText.stringValue = messageText.stringValue.uppercaseString
        let warning = labelText.stringValue
    }
  3. Replace the exclamation marks at the end of each IBOutlet variable with a question mark like this:
    @IBOutlet weak var labelText: NSTextField?
    @IBOutlet weak var messageText: NSTextField?

Notice that Xcode now displays error messages each time you use an IBOutlet variable. That’s because you need to unwrap each optional variable with an exclamation mark like this:

@IBAction func changeCase(sender: NSButton) {
    labelText!.stringValue = messageText!.stringValue.uppercaseString
    let warning = labelText!.stringValue
}

If you define your IBOutlets as regular optional variables (defined by a question mark), then you must unwrap each optional variable with an exclamation mark to access its value.

If you simply define your IBOutlets as implicitly unwrapped optional variables (which Xcode does for you), then you don’t need to type an exclamation mark to unwrap the optional variables.

Basically, let Xcode create your IBOutlets as implicitly unwrapped variables (with an exclamation mark) to make typing Swift code easier.

Now you may wonder when should you use an optional variable (defined by a question mark ?) and when should you use an implicitly unwrapped optional variable defined by an exclamation mark !)?

In general, use implicitly unwrapped optional variables for IBOutlets to make it easy to write Swift code without typing exclamation marks all over. If you use implicitly unwrapped optional variables any other time, your variable could contain a nil value and Xcode won’t catch any potential errors if you try to use it.

To see the danger of using implicitly unwrapped optional variables, follow these steps:

  1. Make sure your IntroductoryPlayground file is loaded in Xcode.
  2. Modify the code as follows:
    import Cocoa

    var safe : Int?  // optional variable
    var danger : Int!// implicitly unwrapped optional variable

    print (danger * 2)
    print (safe * 2)

Notice that neither integer variable has a value in it, but Xcode cheerfully lets you perform a calculation with a nil value in an implicitly unwrapped optional but flags a possible error with a regular optional variable as shown in Figure 5-16.

9781484212349_Fig05-16.jpg

Figure 5-16. Xcode can identify possible problems with undefined optional variables but not undefined implicitly unwrapped optional variables

By making you unwrap optional variables with an exclamation mark (!), Xcode forces you to acknowledge you’re using an optional variable so you can remember to check if it has a nil value or not.

Since implicitly unwrapped optional variables let you type the variable name without typing additional symbols, it’s much easier to forget you’re working with optional variables and check for a possible nil value before trying to use it. Optional variables can’t prevent problems, but they can force you to remember you’re working with potentially nil values.

Summary

If you’re coming from another programming environment, you’ve already seen numerous ways that Swift differs from other languages. Swift’s playground interpreter lets you test your code in a safe environment before copying and pasting it into an actual program. Playgrounds give you the freedom to experiment freely with Swift commands.

You can create single line comments by using the // symbols. You can create multiple line comments by marking the beginning of a comment with the /* symbols and the end of a comment with the */ symbols.

The three most common data types are integers (Int), decimal numbers (Float or Double), and text strings (String). If you need absolute precision with decimal numbers, use Double data types. Otherwise just use Float.

To make data types easier to understand, you can use typealiases, which let you substitute a descriptive name to represent a common data type. To make variable names more flexible, you can use Unicode characters that can represent symbols or foreign language characters.

Storing data in a variable can be as simple as assigning it to a value. Swift also offers computed properties that let you modify a variable or another variable when assigned a new value. Computed properties are far more useful when working with classes and object-oriented programming.

Even more important are optional variables that let you handle nil values without crashing your program. Optional variables are especially important when using IBOutlets to connect Swift code to user interface items such as labels and text fields.

When you create an optional variable (with a question mark), you need to unwrap it to access its actual data (using an exclamation mark).

Variables are crucial for storing data temporarily so you’ll use them often. When you start learning about classes and object-oriented programming, you’ll use variables for defining properties. Essentially, any time you need to store one chunk of data, you’ll declare a variable to hold it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset