Using Standard Types

In this section, you are going to experiment with standard types in an Xcode playground. A playground lets you write code and see the results without the overhead of creating an application and checking the output.

In Xcode, select FileNewPlayground... (or, from the welcome screen, choose Get started with a playground). Make sure the platform is iOS and the template is Blank (Figure 2.2). After clicking Next, you can accept the default name for this file; you will only be here briefly.

Figure 2.2  Configuring a playground

Configuring a playground

When the file opens, notice that the playground is divided into two sections (Figure 2.3). The larger white area to the left is the editor, where you write code. The gray column on the right is the sidebar, where the results of each line of code are shown.

Figure 2.3  A playground

A playground

In the example code, the var keyword denotes a variable, as you saw in your Quiz app, so the value of str can be changed. Type in the code below to change the value of str. When you are done, click the run button that appears next to or under the last line of code, and you will see the results for each line appear in the sidebar to the right. (You can also click the run button next to any other line to run the code only up to that point.)

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"

(We are showing sidebar results to the right of the code for the benefit of readers who are not actively doing the exercise.)

As you saw in Chapter 1, the let keyword denotes a constant value, which cannot be changed. In your Swift code, you should use let unless you expect the value will need to change. Add a constant to the mix and click the run button to see the result. (From now on, assume that you should run new playground code as you enter it.)

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"
let constStr = str                                      "Hello, Swift"

Because constStr is a constant, attempting to change its value will cause an error.

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"
let constStr = str                                      "Hello, Swift"
constStr = "Hello, world"

An error appears, indicated by the red symbol and error message on the offending line. In this case, the error reads Cannot assign to value: 'constStr' is a 'let' constant.

An error in the playground code will prevent you from seeing any further results in the sidebar, so you usually want to address it right away. Remove the line that attempts to change the value of constStr.

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"
let constStr = str                                      "Hello, Swift"
constStr = "Hello, world"

Inferring types

At this point, you may have noticed that neither the constStr constant nor the str variable has a specified type. This does not mean they are untyped! Instead, the compiler infers their types from the initial values. This is called type inference.

You can find out what type was inferred using Xcode’s Quick Help. Option-click constStr in the playground to see the Quick Help information for this constant, shown in Figure 2.4.

Figure 2.4  constStr is of type String

constStr is of type String

Option-clicking to reveal Quick Help will work for any symbol.

Specifying types

If your constant or variable has an initial value, you can rely on type inference. If a constant or variable does not have an initial value or if you want to ensure that it is a certain type, you can specify the type in the declaration.

Add more variables with specified types:

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"
let constStr = str                                      "Hello, Swift"

var nextYear: Int = 0                                   0
var bodyTemp: Float = 0                                 0
var hasPet: Bool = true                                 true

Let’s go over these new types and how they are used.

Number and Boolean types

The most common type for integers is Int. There are additional integer types based on word size and signedness, but Apple recommends using Int unless you really have a reason to use something else.

For floating-point numbers, Swift provides three types with different levels of precision: Float for 32-bit numbers, Double for 64-bit numbers, and Float80 for 80-bit numbers.

A Boolean value is expressed in Swift using the type Bool. A Bool’s value is either true or false.

Collection types

The Swift standard library offers three collections: arrays, dictionaries, and sets.

An array is an ordered collection of elements. The array type is written as Array<T>, where T is the type of element that the array will contain. Arrays can contain elements of any type: a standard type, a structure, or a class.

Add a variable for an array of integers:

var hasPet: Bool = true                                 true
var arrayOfInts: Array<Int> = []                        []

Arrays are strongly typed. Once you declare an array as containing elements of, say, Int, you cannot add a String to it.

There is a shorthand syntax for declaring arrays: You can simply use square brackets around the type that the array will contain. Declare an array of strings using this shorthand:

var hasPet: Bool = true                                 true
var arrayOfInts: Array<Int> = []                        []
var arrayOfStrings: [String] = []                       []

A dictionary is an unordered collection of key-value pairs. The values can be of any type, including structures and classes. The keys can be of any type as well, but they must be unique. Specifically, the keys must be hashable, which allows the dictionary to guarantee that the keys are unique and to access the value for a given key more efficiently. Basic Swift types such as Int, Float, Character, and String are all hashable.

Like Swift arrays, Swift dictionaries are strongly typed and can only contain keys and values of the declared type. For example, you might have a dictionary that stores capital cities by country. The keys for this dictionary would be the country names, and the values would be the city names. Both keys and values would be strings, and you would not be able to add a key or value of any other type.

Add a variable for such a dictionary. (We have split the declaration onto two lines to fit on the printed page; you should enter it on one line.)

var arrayOfStrings: [String] = []                       []
var dictionaryOfCapitalsByCountry:
                Dictionary<String,String> = [:]         [:]

There is a shorthand syntax for declaring dictionaries, too. Update dictionaryOfCapitalsByCountry to use the shorthand:

var arrayOfStrings: [String] = []                       []
var dictionaryOfCapitalsByCountry:
                Dictionary<String,String> = [:]
                [String:String] = [:]                   [:]

A set is similar to an array in that it contains a number of elements of a certain type. However, sets are unordered, and the members must be unique as well as hashable. The unorderedness of sets makes them faster when you simply need to determine whether something is a member of a set. Add a variable for a set:

var winningLotteryNumbers: Set<Int> = []                Set([])

Unlike arrays and dictionaries, sets do not have a shorthand syntax.

Literals and subscripting

Standard types can be assigned literal values, or literals. For example, str is assigned the value of a string literal. A string literal is formed with double quotes. Contrast the literal value assigned to str with the value assigned to constStr:

var str = "Hello, playground"                           "Hello, playground"
str = "Hello, Swift"                                    "Hello, Swift"
let constStr = str                                      "Hello, Swift"

Add two number literals to your playground:

let number = 42                                         42
let fmStation = 91.2                                    91.2

Arrays and dictionaries can be assigned literal values as well. The syntax for creating literal arrays and dictionaries resembles the shorthand syntax for specifying these types.

let countingUp = ["one", "two"]                         ["one", "two"]
let nameByParkingSpace = [13: "Alice", 27: "Bob"]       [13: "Alice", 27: "Bob"]

Swift also provides subscripting as shorthand for accessing arrays. To retrieve an element in an array, you provide the element’s index in square brackets after the array name.

let countingUp = ["one", "two"]                         ["one", "two"]
let secondElement = countingUp[1]                       "two"
...

Notice that index 1 retrieves the second element; an array’s index always starts at 0.

When subscripting an array, be sure that you are using a valid index. Attempting to access an out-of-bounds index results in a trap. A trap is a runtime error that stops the program before it gets into an unknown state.

Subscripting also works with dictionaries – more on that later in this chapter.

Initializers

So far, you have initialized your constants and variables using literal values. In doing so, you created instances of a specific type. An instance is a particular embodiment of a type. Historically, this term has been used only with classes, but in Swift it is used to describe structures and enumerations, too. For example, the constant secondElement holds an instance of String.

Another way of creating instances is by using an initializer on the type. Initializers are responsible for preparing the contents of a new instance of a type. When an initializer is finished, the instance is ready for action. To create a new instance using an initializer, you use the type name followed by a pair of parentheses and, if required, arguments. This signature – the combination of type and arguments – corresponds to a specific initializer.

Some standard types have initializers that return empty literals when no arguments are supplied. Add an empty string, an empty array, and an empty set to your playground.

let emptyString = String()                              ""
let emptyArrayOfInts = [Int]()                          []
let emptySetOfFloats = Set<Float>()                     Set([])

Other types have default values:

let defaultNumber = Int()                               0
let defaultBool = Bool()                                false

Types can have multiple initializers. For example, String has an initializer that accepts an Int and creates a string based on that value.

let number = 42                                         42
let meaningOfLife = String(number)                      "42"

To create a set, you can use the Set initializer that accepts an array literal:

let availableRooms = Set([205, 411, 412])               {412, 205, 411}

Float has several initializers. The parameter-less initializer returns an instance of Float with the default value. There is also an initializer that accepts a floating-point literal.

let defaultFloat = Float()                              0
let floatFromLiteral = Float(3.14)                      3.14

If you use type inference for a floating-point literal, the type defaults to Double. Create the following constant with a floating-point literal:

let easyPi = 3.14                                       3.14

Use the Float initializer that accepts a Double to create a Float from this Double:

let easyPi = 3.14                                       3.14
let floatFromDouble = Float(easyPi)                     3.14

You can achieve the same result by specifying the type in the declaration.

let easyPi = 3.14                                       3.14
let floatFromDouble = Float(easyPi)                     3.14
let floatingPi: Float = 3.14                            3.14

Properties

A property is a value associated with an instance of a type. For example, String has the property isEmpty, which is a Bool that tells you whether the string is empty. Array<T> has the property count, which is the number of elements in the array as an Int. Access these properties in your playground:

let countingUp = ["one", "two"]                         ["one", "two"]
let secondElement = countingUp[1]                       "two"
countingUp.count                                        2
...
let emptyString = String()                              ""
emptyString.isEmpty                                     true
...

Instance methods

An instance method is a function that is specific to a particular type and can be called on an instance of that type. Try out the append(_:) instance method from Array<T>. You will first need to change your countingUp array from a constant to a variable.

let countingUp = ["one", "two"]
var countingUp = ["one", "two"]                         ["one", "two"]
let secondElement = countingUp[1]                       "two"
countingUp.count                                        2
countingUp.append("three")                              ["one", "two", "three"]

The append(_:) method accepts an element of the array’s type and adds it to the end of the array.

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

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