Getting Your Feet Wet with Swift: Variables, Constants, and Loops

Getting Your Feet Wet with Swift: Variables, Constants, and Loops


Swift is a new programming language created by Apple, with the intention of making development of software for Apple products significantly easier. 

If you have experience in C and Objective-C, you should find Swift to be a walk in the park. 

All the classes and types that are available to you in C and Objective-C are ported over and available in their exact incarnations in Swift.

If, however, you come from a Ruby or Python background, you will find Swift’s syntax to be right up your alley. Swift borrows and iterates on many ideas from Python and Ruby.

If you come from the JavaScript world, you will be pleased to know that Swift also doesn’t ask you to declare types, as old strict Java does. 

You will also be pleased to know that Swift has its own version of indexOf and many other familiar JavaScript functions. 

If they aren’t the exact replicas of said functions, they will at least be familiar.

If you come from the Java world, you will be happy to know that even though Swift does not force you to declare types, you still can and Swift most certainly enforces those types, very strictly.

These are all just basic syntax comparisons; the real magic evolves from Swift’s chameleon-like capability to be written in any way that makes you the programmer comfortable. 

If you want to write the tersest one-liner that does everything you ever needed in one fell swoop, Swift has you covered. 

If you want to write Haskell-like functional programming, Swift can do that, too. 

If you want to write beautiful object-oriented programming with classic design patterns, Swift will do that as well.

In the future (or now, depending on when you are reading this), Swift will be open source so that you can officially (theoretically) write Swift on Linux or Windows. 

Someone may even create a web framework like Ruby on Rails in Swift.

This chapter covers the basic building blocks of Swift. It starts with variables and constants. 

With this knowledge, you will be able to store whatever you’d like in memory. 

Swift has a special feature called optionals, which allows you to check for nil values in a smoother way than in other programming languages. 

As I briefly mentioned before, Swift has strong type inference; this allows you to have strict typing without needing to declare a type. 

This chapter also goes over how Swift handles loops and if/else statements.

Building Blocks of Swift

Swift allows you to use variables and constants by associating a name with a value of some type. 

For example, if you want to store the string "Hi" in a variable named greeting, you can use a variable or a constant. 

You create a variable by using the var keyword. 

This establishes an associated value that can be changed during the execution of the program. In other words, it creates a mutable storage. 

If you do not want mutable storage, you can use a constant. For example, you might record the number of login retries a user is allowed to have before being refused access to the site. 

In such a case, you would want to use a constant, as shown in this example:

var hiThere = "Hi there"
hiThere = "Hi there again"

let permanentGreeting = "Hello fine sir"
permanentGreeting = "Good morning sir"

Notice that you don’t use a semicolon as you would in many other languages. 

Semicolons are not mandatory, unless you want to combine many statements together on the same line. 

In Swift you would not put a semicolon on the end of the line, even though Swift will not complain

Here is an example that shows you when you would use the semicolon in Swift when multiple lines are combined into one:

let numberOfRetries = 5; var currentRetries = 0

Also unique to Swift, you can use almost any Unicode character to name your variables and constants. 

Developers can name resources using Hebrew, Simplified Chinese, and even special Unicode characters, such as full-color koala emoji.

When declaring multiple variables, you can omit the var keyword. Here is an example:

var yes = 0, no = 0

Computed Properties (Getters and Setters)

In Swift you can also declare variables as computed properties. 

You would use this when you want to figure out the value of the variable at runtime. 

Here is an example of a getter, where the value of the score is determined by how much time is left. 

In this example we are creating a read-only computed property.

var timeLeft = 30
var score:Int {
get{
    return timeLeft * 25
}
}
print(score)

In this example we can reference (or read) score anywhere because it is in the global scope. 

What is really interesting is that if we try to set the score, it will give us an error because we have created a read-only property. 

If we want to be able to set this property, we need to create a setter. You cannot create a setter without a getter. 

Aside from the fact that it would not make sense, it also just will not work. 

Let’s create a setter to go along with our getter. It does not make sense for a setter to set the computed property directly because the value of the property is computed at runtime. 

Therefore, you use a setter when you want to set other values as a result of the setter being set. 

Also, setters work well in some sort of organizational unit, which we haven’t covered yet, but it’s worth diving into briefly. Here is a full Swift example, which includes many elements we have not covered yet.

import UIKit
struct Book {
    var size = CGSize()
    var numberOfPages = 100;
    var price:Float {
    get{
        return Float(CGFloat(numberOfPages) * (size.width * size.height))
    }
    set(newPrice){
        numberOfPages = Int(price / Float(size.width * size.height))
    }
    }
}

var book = Book(size: CGSize(width: 0.5, height: 0.5), numberOfPages: 400)
print(book.price)
book.price = 400
print(book.numberOfPages)

In this example we create a book Struct, which is a way to organize code so that it is reusable. 

I would not expect you to understand all of this example, but if you have ever coded in any other languages, you will notice that there is a lot of type casting going on here. 

Type casting is a something you do all the time in Objective-C and most other languages. 

We will cover all aspects of this code in this book, but you should know that we created a setter, which sets the number of pages in the book relative to the new price.

Using Comments

You indicate comments in Swift by using a double forward slash, exactly as in Objective-C. Here’s an example:

// This is a comment about the number of retries
let numberOfRetries = 5 // We can also put a comment on the end of a line.

If you want to create comments that span multiple lines, you can use this /* */ style of comments, which also works well for documentation.

/* Comments can span
multiple lines */

Inference

Swift uses inference to figure out what types you are trying to use. Because of this, you do not need to declare a type when creating variables and constants. 

However, if you want to declare a type you may do so, and in certain situations, it is absolutely necessary. 

When declaring a variable, the rule of thumb is that Swift needs to know what type it is. 

If Swift cannot figure out the type, you need to be more explicit. The following is a valid statement:

var currentRetries = 0

Notice that Swift has to figure out what type of number this is. currentRetries may be one of the many types of numbers that Swift offers (Swift will infer this as an Int in case you are wondering, but more on that later). You could also use this:

var currentRetries:Int = 0

In this case, you explicitly set the type to Int by using the colon after the variable name to declare a type. 

Although this is legit, it is unnecessary because Swift already knows that 0 is an Int. Swift can and will infer a type on a variable that has an initial value.

When do you need to declare the type of a variable or constant? 

You need to declare the type of a variable or constant if you do not know what the initial value will be. For example:

var currentRetries:Int

In this case, you must declare Int because without it, Swift cannot tell what type this variable will be. This is called type safety. 

If Swift expects a string, you must pass Swift a string. You cannot pass an Int when a String is expected. This style of coding is a great time-saver. 

You will do a lot less typing with your fingers and a lot more thinking with your brain. 

Every default value you give a variable without a type will be given a type. Let’s talk about numbers first.

For number types, Swift gives us the following:

  • Int is available in 8, 16, 32, and 64 bits, but you will most likely stay with just Int. It’s probably large enough for your needs. Here’s what you need to know about Int:

    Int on 32-bit platforms is Int32.

    Int on 64-bit platforms is Int64.

    That is, when you declare a variable as Int, Swift will do the work of changing that to Int32 or Int64. You don’t need to do anything on your end.

    Int can be both positive and negative in value.

    Int will be the default type when you declare a variable with a number and no decimals:

    var someInt = 3 // this will be an Int

    UInt is provided as an unsigned integer. An unsigned number must be positive, whereas a signed number (an Int) can be negative. 

  • For consistency, Apple recommends that you generally use Int even when you know that a value will never be negative.

  • Double denotes 64-bit floating-point numbers. Double has a higher precision than float, with at least 15 decimal digits. Double will be the chosen type when you declare a variable that has decimals in it:

    var someDouble = 3.14 // this will be a double

    Combining any integer with any floating-point number results in a Double:

    3 + 3.14 // 6.14 works and will be a double
    var three = 3
    var threePointOne = 3.1
    three + threePointOne //Error because you can't mix types
  • Float denotes 32-bit floating-point numbers. Float can have a precision as small as 6. 
  • Whether you choose Float or Double is completely up to you and your situation. Swift will choose Double when no type is declared.

Along with Decimal numbers, you can use BinaryOctal, and Hexadecimal numbers:

  • Decimal is the default for all numbers, so no prefix is needed.
  • Create a Binary number by adding a 0b prefix.
  • Octal uses a 0o prefix.
  • Hexadecimal uses a 0x prefix.

You can check the type of the object by using the is keyword. The is keyword will return a Boolean. 

In this example we use the Any class to denote that pi can be anything at all until we type it as a Float:

var pi:Any?
pi = 3.141
pi is Double //true
pi is Float  //false

Notice that you declare this type as Any? 

in the preceding example. The question mark denotes an optional, which allows us to not set an initial value without causing an error. 

The Any type can be any type (exactly what it says). Objective-C is not as strict as Swift, and you need to be able to intermingle the two languages. 

For this purpose, Any and AnyObject were created, which allows you to put any type in an object. 

Think about arrays in Objective-C, which can mix different types together; for that purpose you need to give Swift the ability to have arrays of different types. You’ll learn more about this later in the chapter.

Swift is the only programming language (that I know of) that lets you put underscores in numbers to make them more legible.

 Xcode ignores the underscores when it evaluates your code. You might find using underscores especially useful with big numbers when you want to denote a thousand-comma separator, as in this case:

var twoMil = 2_000_000

Before you can add two numbers together, they must be made into the same type. For example, the following will not work:

var someNumA:UInt8 = 8
var someNumB:Int8 = 9
someNumA + someNumB
//Int8 is not convertible to UInt8

The reason this does not work is that someNumA is a UInt8 and someNumB is an Int8. Swift is very strict about the combination of things.

To make this work, you must convert one of the types so that the two types are the same. 

To do this, use the initializer of the type. For example, you can use the initializer UInt8, which can convert someNumB to a UInt8 for you:




someNumA + UInt8(someNumB)

Swift is strict and makes sure that you convert types before you can combine them.

We had to do a lot of conversions of types in a previous example.

----------------------------------------------------------------------------------------------------------------------------------------------------------

Merging Variables into a String

When you want to combine a variable in a string there is a special syntax for that. 

Take an example in which you have a variable message and you want to mix it into a string. In Objective-C you would do something like this:

[NSString stringWithFormat:@"Message was legit: %@", message];

In JavaScript you would do something like this:

"Message was legit:" + message;

In Python you would do something like this:

"Message was legit: %s" % message

In Ruby you would do something like this:

"Message was legit: #{message}"

In Swift you do something like this:

"Message was legit: \(message)"

You use this syntax of \() to add a variable into a string. Of course, this will interpret most things you put in between those parentheses. 

This means you can add full expressions in there like math. For example:

"2 + 2 is \(2 + 2)"

This makes it very simple to add variables into a string. Of course, you could go the old-school way and concatenate strings together with the plus operator. 

In most situations you don’t need to do this because the \() makes things so much easier. 

One thing to remember is that Swift has strict type inference, so if you try to combine a String with an Int, Swift will complain. The error it gives is not the easiest to decipher. For example:

"2 + 2 is " + (2 + 2)

This returns the following error (depending on your version of Swift and how you are running it):

<stdin>:3:19: error: binary operator '+' cannot be
applied to operands of type 'String' and 'Int'
print("2 + 2 is " + (2 + 2))
~~~~~~~~~~~ ^ ~~~~~~~
<stdin>:3:19: note: overloads for '+' exist with these
partially matching parameter lists: (Int, Int),
(String, String), (UnsafeMutablePointer<Memory>,
Int), (UnsafePointer<Memory>, Int)
print("2 + 2 is " + (2 + 2))

What this means is that you can’t mix Strings and Ints. So you have to convert the Int to a String.

"2 + 2 is " + String(2 + 2)

This works because you are now combining a String and an Int. One of the most important things to keep in mind when writing Swift is that you’ll often do a lot of type conversion to deal with the strict typing.

-----------------------------------------------------------------------------------------------------------------------------------------------------------

Optionals: A Gift to Unwrap

In our tour through the basic building blocks of Swift, we come to optionals. Optionals are a unique feature of Swift, and they are used quite extensively. 

Optionals allow you to safely run code where a value may missing, which would normally cause errors. Optionals take some getting used to. 

Optionals help you achieve clean-looking code with fewer lines while also being stricter.

In many languages, you need to check objects to see whether they are nil or null

Usually, you write some pseudo-code that looks like the following. In this example we check for not null in JavaScript:

if(something != null) {...

In Swift, an optional either contains a value or it doesn’t. In other languages, we often have to deal with missing values, such as a variable that once contained a value but no longer does. 

Or when a variable is initialized without a value. To mark something as optional, you just include a ? next to the type of the object. For example, here’s how you create a String optional:

var someString:String? = "Hey there!"

You can now say that someString is of type String? (a “String optional”) and no longer just of type String. Try printing that variable as an optional string and then as a regular string. Notice the difference in their returned values.

var greetingOptional:String? = "hi there"
var greeting:String = "Hi"
print(greetingOptional) //Optional("hi there")
print(greeting) //"Hi"

If you choose to use an optional and it does contain a value, you must do something special to get raw value out. 

Optionals must be “unwrapped” in order to get their value back. 

There are a couple ways to get the value out of an optional. When you see a variable of type String?, you can say that this variable may or may not contain a value. 

You will test this String optional to find out whether it does in fact have a value. 

How do you test an optional? There are a couple of ways. First try to use value binding.

Value binding allows you to do two things. First, it allows you to test the optional to see whether it is nil (whether it contains a value). 

Second, if that variable is not nil, value binding allows you to grab the value out of the optional and have it passed into a constant as a locally scoped variable. 

To see this in action, take a look at an example, but before you can try it out, you first need to open a new playground:

  1. Open Xcode.
  2. Click Get started with a playground.
  3. Save a new playground file by giving it a filename.

Now you can try out value binding with optionals:

var hasSomething:String? = "Hey there!"
if let message = hasSomething {
    "Message was legit: \(message)"
} else {
    "There was no message!"
}

A couple of new things are going on here. Let’s go through this example one step at a time:

  1. On the first line, you create a variable as usual, but you add the ? to say that this is a String optional. This means that this String may contain a value or nil. In this case, it contains a value. That value is the string "Hey there!".
  2. Next, you write an if statement. You are testing whether the variable hasSomething is nil. At the same time, you are assigning that value of the optional to a constant message. If the variable contains a value, you get a new constant (available only in the local scope, so we call it a locally scoped constant), which is populated with the raw value of the optional. You will then enter into the if statement body.
  3. If you do enter into that if statement, you now have a message to use. This constant will be available only in that if statement.

However, sometimes you are absolutely sure that your optional contains a value and is not empty. 

You can think of optionals as a gift that needs to be unwrapped. 

If an optional is nil inside, it will not throw an error when you use it. In other languages, trying to access something of nil (or null) value throws an error.

You can unwrap an optional by using an exclamation point. That is, you can get the value inside the optional by using an exclamation point. Let’s look again at our earlier example:

var hasSomething:String? = "Hey there!"
print(hasSomething) // Optional("Hey there!")\n
// Now unwrap the optional with the "!"
print(hasSomething!) // "Hey there!\n"

If you were sure that the string contained a value, you could unwrap the optional with the “!.” 

Now you can get the value out of the optional with one extra character. Remember how we said optionals are like wrapped-up presents? 

Well, it’s sometimes good to think of them more like bombs in Minesweeper. 

If you are too young for Minesweeper, think of them as presents that could contain bombs. You want to unwrap an optional with the “!” 

only if you are absolutely sure it contains a value. You want to unwrap an optional with the “!” 

only if you are absolutely sure it does not contain nil

If you unwrap an optional that’s nil, using “!,” then you will throw a fatal error, and your program will crash:

var hasSomething:String? //declare the optional string with no initial
   value
// Now try and force it open
hasSomething! // fatal error:
Execution was interrupted, reason: EXC_BAD_INSTRUCTION...

When you get an EXC_BAD_INSTRUCTION somewhere, it means that your app is trying to access something that does not exist, which could be an error with an empty optional trying to unwrap with the “!.”

Printing Your Results

When you use the playground to test your code, you have two options for printing data. You can simply just write it, like this:

var someString = "hi there"
someString //prints "hi there" in the output area

You can also use print(), which prints to the console output area. When you are making a full-fledged app, compiling code outside a playground, you’ll want to use print(), like this, because just writing the variable will not do anything:

var someString = "hi there"
print(someString) //prints "hi there" in the console output

Implicitly Unwrapped Optionals

Sometimes you want to create an optional that gets unwrapped automatically. To do this, you assign the type with an exclamation point instead of a question mark:

var hasSomething:String! = "Hey there"// implicitly unwrapped optional string
hasSomething // print the implicitly unwrapped optional and get the
   unwrapped value.

You can think of implicitly unwrapped optionals as a present that unwraps itself. 

You should not use an implicitly unwrapped optional if a chance exists that it may contain nil at any point. 

You can still use implicitly unwrapped optionals in value binding to check their values.

So why should you create implicitly unwrapped optionals in the first place if they can be automatically unwrapped? 

How does that make them any better than regular variables? Why even use them in the first place? 

These are fantastic questions, and we will answer them later, after we talk about classes and structures in Chapter 4,

 “Structuring Code: Enums, Structs, and Classes.” One quick answer is that sometimes we want to say that something has no value initially but we promise that it will have a value later.

 Properties of classes must be given a value by the time initialization is complete. 

We can declare a property with the exclamation point to say, in effect, “Right now it does not have a value, but we promise we will give this property a value at some point.”

Also, sometimes you will have a constant that cannot be defined during initialization, and sometimes you will want to use an Objective-C API. For both of these reasons and more, you will find yourself using implicitly unwrapped optionals. 

The following example has two examples (with some concepts not covered yet) in which you would commonly use implicitly unwrapped optionals.

class SomeUIView:UIView {
    @IBOutlet var someButton:UIButton!
    var buttonWidth:CGFloat!

    override func awakeFromNib() {
        self.buttonOriginalWidth = self.button.frame.size.width
    }
}

In this example you have a button, which you cannot initialize yourself because the button will be initialized by Interface Builder. 

Also, the width of the button is unknown at the time of the creation of the class property, so you must make it an implicitly unwrapped optional. 

You will know the width of the button after awakeFromNib runs, so you promise to update it then.

------------------------------------------------------------------------------------------------------------------------------------------------

Tuples

Using tuples (pronounced “TWO-pulls” or “TUH-pulls”) is a way to group multiple values into one value. Think of associated values. Here is an example with URL settings:

let purchaseEndpoint = ("buy","POST","/buy/")

This tuple has a String, a String, and a String. This tuple is considered to be of type (StringStringString). You can put as many values as you want in a tuple, but you should use them for what they are meant for and not use them like an array or a dictionary. You can mix types in tuples as well, like this:

let purchaseEndpoint = ("buy","POST","/buy/",true)

This tuple has a String, a String, a String, and a Bool. You are mixing types here, and this tuple is considered to be of type (StringStringStringBool). You can access this tuple by using its indexes:

purchaseEndpoint.1 // "POST"
purchaseEndpoint.2 // "/buy/"

This works well but there are some inconveniences here. You can guess what POST and /buy/ are, but what does true stand for? 

Also, using indexes to access the tuple is not very pretty or descriptive. You need to be able to be more expressive with the tuple.

You can take advantage of Swift’s capability to name individual elements to make your intentions clearer:

let purchaseEndpoint = (name: "buy", httpMethod: "POST",URL: "/buy/",useAuth: true)

This tuple has StringStringString, and Bool (true or false) values, so it is the same type as the previous tuple. 

However, now you can access the elements in a much more convenient and descriptive way:

purchaseEndpoint.httpMethod = "POST"

This is much better. It makes much more sense and reads like English.

You can decompose this tuple into multiple variables at once. Meaning you can take the tuple and make multiple constants or variables out of it in one fell swoop. 

So if you want to get the name, the httpMethod, and the URL into individual variables or constants, you can do so like this:

let (purchaseName, purchaseMethod, purchaseURL, _) = purchaseEndpoint

Here, you are able to take three variables and grab the meat out of the tuple and assign it right to those variables. 

You use an underscore to say that you don’t need the fourth element out of the tuple. 

Only three out of the four properties of the tuple will be assigned to constants.

In Chapter 3, “Making Things Happen: Functions,” you will use tuples to give functions multiple return values. Imagine having a function that returned a tuple instead of a string. 

You could then return all the data at once and do something like this:

func getEndpoint(endpoint:String) ->
    (description: String, method: String, URL: String) {
    return (description: endpoint, method: "POST", URL: "/\(endpoint)/")
}
let purchaseEndpoint = getEndpoint("buy")
print("You can access the
    \(purchaseEndpoint.description) endpoint at the URL \(purchaseEndpoint.URL)")

----------------------------------------------------------------------------------------------------------------------------------------------------------

Number Types

Swift is interoperable with Objective-C, so you can use C, Objective-C, and Swift types and code all within Swift. 

As discussed earlier in the chapter, when you write a variable using an integer, Swift automatically declares it with a type Int, without your having to tell Swift you want an Int. In this example, you don’t tell Swift to make this variable an Int:

let theAnswerToLifeTheUniverseAndEverything = 42

Rather, Swift infers that it is an Int. Remember that on 32-bit systems this Int will be an Int32, and on 64-bit systems it will be an Int64

If you don’t remember that it won’t matter because Swift will convert this for you automatically anyway. Even though you have many different Int types available to you, 

unless you need an Int of a specific size, you should stick with Swift’s Int. When we say Int32, what we mean is a 32-bit integer. 

(This is similar to C.) You can also use UInt for unsigned (non-negative) integers, but Apple recommends that you stick with Int even if you know that your variable is going to be unsigned.

Again, when you write any type of floating-point number (a number with a decimal), and you don’t assign a type, Swift automatically declares it with the type Double

Swift also gives you Double and Float types. The difference between them is that Double has a higher precision of around 15 decimal digits, whereas Float has around 6. Here is an example of a Double in Swift:

let gamma = 0.57721566490153286060651209008240243104215933593992

Swift is strict about its types and they get combined together. If something is meant to be a String, and you give it an Int, then you will get an error. 

Swift needs you to be explicit with types. For example, this will not work:

var someInt = 5 // Inferred to be an Int
someInt + 3.141 // throws an error

This throws an error because you can’t combine an Int and a Double. If you want to combine an Int and a Double, you must first convert the Int to a Double or vice versa, depending on your preference. 

Here we combine an Int and a Double by converting the Int to a Double:

var someInt = 5 // Inferred to be an Int
Double(someInt) + 3.141 // 8.141

var someInt = 5 // Inferred to be an Int
Float(someInt) + 3.141 // In this case 3.141 will be inferred to be a Float so
// it can combine with a Float

var someInt = 5 // Inferred to be an Int
Float(someInt) + Double(3.141) //This will throw an error and will not work

You can use the initializer (Float(someInt) or Double(someInt), etc.) of the number type to convert between types. For example, you can use Float() to convert any number type into a Float.

So again, when you want to perform any operations on two or more number types, all sides of the operation must be of the same type. 

You’ll see this pattern often in Swift, and not just with numbers. For example, you cannot directly add a UInt8 and a UInt16 unless you first convert the UInt8 to a UInt16 or vice versa.

------------------------------------------------------------------------------------------------------------------------------------------------------


From Objective-C to Swift

If you are coming from the world of Objective-C and C, you know that you have many number types at your disposal.

 Number types like CGFloat and CFloat are necessary to construct certain objects. 

For example, SpriteKit has the SKSpriteNode as a position property, which uses a CGPoint with two CGFloats.

What is the different between CGFloat and Float? In this specific case we found that CGFloat is just a typealias for Double. This is what the code actually says:

typealias CGFloat = Double

What is a typealias? Great question. A typealias is just a shortcut to get to an already existing type by giving it a substitute name. You could give String an alternative name type of Text, like this:

typealias Text = String
var hello:Text = "Hi there"

Now hello is of type Text, which never existed before this point. So if CGFloat is a typealias for a Double, this just means that when you make CGFloats, you are really just making Doubles. 

It’s worth it to Command+click around and see what is mapping to what. For example, a CFloat is a typealias for Float, and a CDouble is a typealias for Double.

That does not mean that you can suddenly add them together. You still need to convert them to combine them. 

For example, this will not work:

var d = 3.141
var g = CGFloat(3.141)
print(d + g)

To fix this example we would need to do something like this:

var d = 3.141
var g = CGFloat(3.141)
print(CGFloat(d) + g)

Control Flow: Making Choices

Controlling the order in which your code executes is obviously a crucial aspect of any programming language. 

By building on the traditions of C and C-like languages, Swift’s control flow constructs allow for powerful functionality while still maintaining a familiar syntax.

for Loops

At its most basic, a for loop allows you to execute code over and over again. 

This is also called “looping.” How many times the code gets executed is up to you (maybe infinitely). 

In the Swift language, there are two distinct types of for loops to consider. 

There is the traditional for-condition-increment loop, and there is the for-in loop. for-in is often associated with a process known as fast enumeration—a simplified syntax that makes it easier to run specific code for every item. 

for-in loops give you far less code to write and maintain than your typical C for loops.

for-condition-increment Loops

You use a for-condition-increment loop to run code repeatedly until a condition is met. 

On each loop, you typically increment a counter until the counter reaches the desired value. 

You can also decrement the counter until it drops to a certain value, but that is less common. The basic syntax of this type of loop in Swift looks something like this:

for initialization; conditional expression; increment {
    statement
}

As in Objective-C and C, in Swift you use semicolons to separate the different components of the for loop. 

However, Swift doesn’t group these components into parentheses. Aside from this slight syntactic difference, for loops in Swift function as they would in any C language.

Here’s a simple example of a for-condition-increment loop that simply prints Hello a few times:

for var i = 0; i < 5; ++i {
    print("Hello there number \(i)")
}
// Hello there number 0
// Hello there number 1
// Hello there number 2
// Hello there number 3
// Hello there number 4

This is fairly straightforward, but notice the following:

  • Variables or constants declared in the initialization expression only exist within the scope of the loop. If you need to access these values outside the scope of the for loop, then the variable must be declared prior to entering the loop, like this:

    var i = 0
    for i; i < 5; ++i {...
  • If you’re coming from another language, particularly Objective-C, you will notice that the last example uses ++i instead of i++. Using ++i increments i before returning its value, whereas using i++ increments i after returning its value. Although this won’t make much of a difference in the earlier example, Apple specifically suggests that you use the ++i implementation unless the behavior of i++ is explicitly necessary.

for-in Loops and Ranges

In addition to giving you the traditional for-condition-increment loop, Swift builds on the enumeration concepts of Objective-C and provides an extremely powerful for-in statement. 

You will most likely want to use for-in for most of your looping needs because the syntax is the most concise and also makes for less code to maintain.

With for-in, you can iterate numbers in a range. For example, you could use a for-in loop to calculate values over time. Here you can loop through 1 to 4 with less typing:

class Tire{}
var tires = [Tire]()
for i in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

We haven’t covered the class and array syntax yet, but maybe you can take a guess at what they do. 

This example uses a ... range operator for a closed range. The range begins at the first number and includes all the numbers up to and including the second number.

Swift also provides you with the half-open range operator, which is written like this:

1..<4

This range operator includes all numbers from the first number up to but not including the last number. 

The previous example, rewritten to use the non-inclusive range operator, would look like this:

class Tire{}
var tires = [Tire]()
for i in 1..<5 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

As you can see, the results are almost identical and both examples provide concise and readable code. 

When you don’t need access to i, you can disregard the variable altogether by replacing it with an underscore (_). The code now might look something like this:

class Tire { }
var tires = [Tire]()
// 1,2,3, and including 4

class Tire {}
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

Let’s pretend that a bunch of tires have gone flat, and you need to refill each tire with air. 

We could use the for in loop to loop through all of our tires in the tire array. 

We can add on to our earlier example by giving the tires air. You could do something like this:

class Tire { var air = 0 }
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

for tire in tires {
    tire.air = 100
    print("This tire is filled \(tire.air)%")
}
print("All tires have been filled to 100%")

With this type of declaration, Swift uses type inference to assume that each object in an array of type [Tire] will be a Tire

This means it is unnecessary to declare the type Tire explicitly. In a situation in which the array’s type is unknown, the implementation would look like this:

class Tire { var air = 0 }
var tires = [Tire]()
for _ in 1...4 {
    tires.append(Tire())
}
print("We have \(tires.count) tires")

for tire: Tire in tires {
    tire.air = 100
    print("This tire has been filled to \(tire.air)%")
}

In this example we told the loop that each tire in the array of tires is going to be specifically of type Tire

In this specific example there is not a good reason to do this, but you may come upon a situation in which the type is not set explicitly. 

Since Swift must know what types it is dealing with, you should make sure that you communicate that information to Swift.

Looping Through Other Types

In Swift, a String is really a collection of Character values in a specific order. You can iterate values in a String by using a for-in statement, like so:

for char in "abcdefghijklmnopqrstuvwxyz".characters {
    print(char)
}
// a
// b
// c
// etc....

As long as something conforms to the SequenceType, you can loop through it. 

You cannot loop through the string directly; you need to access its character property.

When looping, there will be situations in which you will need access to the index as well as the object. 

One option is to iterate through a range of indexes and then get the object at the index. You would write that like this:

let numbers  = ["zero", "one", "two", "three", "four"]
for idx in 0..<numbers.count {
    let numberString = array[idx]
    print("Number at index \(idx) is \(numberString)")
}
// Number at index 0 is zero
// Number at index 1 is one
// etc....

This works just fine, but Swift provides a much swifter way to do this. 

Swift gives you an enumerate method as part of the array, which makes this type of statement much more concise. Let’s use the for-in statement in with the enumerate method:

let numbers = ["zero", "one", "two", "three", "four"]
for (i, numberString) in numbers.enumerate() {
    print("Number at index \(i) is \(numberString)")
}
// Number at index 0 is zero
// Number at index 1 is one
// etc....

This is much clearer, and you would use it when you require an array element and its accompanying index. 

You can grab the index of the loop and the item being iterated over!

Up to this point, all the loops we’ve covered know beforehand how many times they will iterate. 

For situations in which the number of required iterations is unknown, you’ll want to use a while loop or a do while loop. The syntax to use these while loops is very similar to that in other languages. Here’s an example:

var i = 0
while i < 10 {
    i++
}

This says that this loop should increment the value of i while it is less than 10. In this situation, i starts out at 0, and on each run of the loop, i gets incremented by 1. 

Watch out, though, because you can create an infinite loop this way. There will be times when you really need an infinite loop.

One way to create an infinite while loop is to use while true:

while true {
}

In this example you use a while loop that always evaluates to true, and this loop will run forever, or until you end the program or it crashes itself.

This next example uses some of the looping capabilities plus if/else statements to find the prime numbers. 

Here’s how you could find the 200th prime number:

var primeList = [2.0]
var num = 3.0
var isPrime = 1
while primeList.count < 200 {
    var sqrtNum = sqrt(num)
    // test by dividing only with prime numbers
    for primeNumber in primeList {
        // skip testing with prime numbers greater
        // than square root of number
        if num % primeNumber == 0 {
            isPrime = 0
            break
        }
        if primeNumber > sqrtNum {
            break
        }
    }
    if isPrime == 1 {
        primeList.append(num)
    } else {
        isPrime = 1
    }
    //skip even numbers
    num += 2
}
print(primeList)

Grabbing primeList[199] will grab the 200th prime number because arrays start at 0. 

You can combine while loops with for-in loops to calculate prime numbers.

To if or to else (if/else)

It’s important to be able to make decisions in code. 

It’s okay for you to be indecisive but you wouldn’t want that for your code. Let’s look at a quick example of how to make decisions in Swift:



let carInFrontSpeed = 54
if carInFrontSpeed < 55 {
    print("I am passing on the left")
} else {
    print("I will stay in this lane")
}

You use Swift’s if and else statements to make a decision based on whether a constant is less than 55. 

Since the integer 54 is less than the integer 55, you print the statement in the if section.

One caveat to if statements is that in some languages you can use things that are “truthy,” like 1 or a non-empty array. That won’t work in Swift. 

You must conform to the protocol BooleanType. To make this simple, you must use true or false. For example, here are some examples that will not work:

if 1 { // 1 in an Int and can't be converted to a boolean
    //Do something
}
var a = [1,2,3]
if a.count{ // a.count is an Int and can't be converted to a boolean
    print("YES")
}

If you want to make these examples work, you would have to convert those numbers to a Bool

For example, check out what happens when we convert some simple integers to Booleans.

print(Bool(1)) // true
print(Bool(2)) // true
print(Bool(3)) // true
print(Bool(0)) // false

If Ints can be converted into Bools, you can check for if with a truthy value if you first convert it to a Bool

Let’s rewrite our previous failing examples and make them work.

if Bool(1) { // 1 in an Int and can't be converted to a boolean
    print("Duh it works!")
}
var a = [1,2,3]
if Bool(a.count){ // a.count is an Int and can't be converted to a boolean
    print("YES")
}

We were able to check for 1 and an array count in the if statement because we first converted them to Bools.

You may also want to check multiple statements to see whether they’re true or false

You want to check whether the car in front of you slows down below 55 mph, whether there is a car coming, and whether there is a police car nearby. 

You can check all three in one statement with the && operator. This operator states that both the statement to its left and the one to its right must be true. Here’s what it looks like:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
if !policeNearBy && !carInLane3 && carInFrontSpeed < 55 {
    print("We are going to pass the car.")
} else {
    print("We will stay right where we are for now.")
}

Your code will make sure that all three situations are false before you move into the next lane (the else).

Aside from the and operator, you also have the or operator. You can check to see whether any of the statements is true by using the or operator, which is written as two pipes: ||

You could rewrite the preceding statement by using the or operator. This example just checks for the opposite of what the preceding example checks for:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
if policeNearBy || carInLane3 || carInFrontSpeed > 55 {
    print("We will stay right where we are for now.")
} else {
    print("We are going to pass the car.")
}

If any of the preceding variables is true, you will stay where you are; you will not pass the car.

Aside from just if and else, you may need to check for other conditions. 

You might want to check multiple conditions, one after the other, instead of just going straight to an else

You can use else if for this purpose, as shown in this example:

var policeNearBy = false
var carInLane3 = false
var carInFrontSpeed = 45
var backSeatDriverIsComplaining = true
if policeNearBy || carInLane3 || carInFrontSpeed > 55 {
    print("We will stay right where we are for now.")
} else if backSeatDriverIsComplaining {
    print("We will try to pass in a few minutes")
}else {
    print("We are going to pass the car.")
}

You can group as many of these else ifs together as you need. 

However, when you start grouping a bunch of else if statements together, it might be time to use the switch statement.

Switching It Up: switch Statements

You can get much more control and more readable code if you use a switch statement. 

Using tons of if else statements might not be as readable. Swift’s switch statements are very similar to those in other languages with extra power added in. 

The first major difference with switch statements in Swift is that you do not use the break keyword to stop a condition from running through each case statement. 

Swift automatically breaks on its own when the condition is met.

Another caveat about switch statements is that they must be absolutely exhaustive. That is, if you are using a switch statement on an int, you need to provide a case for every int ever. 

This is not possible, so you can use the default statement to provide a match when nothing else matches. Here is a basic switch statement:

var num = 5
switch num {
case 2:print("It's two")
case 3:print("It's three")
default:print("It's something else")
}

This tests the variable num to see whether it is 2, 3, or something else. 

Notice that you must add a default statement. As mentioned earlier, if you try removing it, you will get an error because the switch statement must exhaust every possibility. 

Also note that case 3 will not run if case 2 is matched because Swift automatically breaks for you.

You can also check multiple values at once. This is similar to using the or operator (||) in if else statements. Here’s how you do it:

var num = 5
switch num {
case 2,3,4:print("It's two") // is it 2 or 3 or 4?
case 5,6:print("It's five") // is it 5 or 6?
default:print("It's something else")
}

In addition, you can check within ranges. The following example determines whether a number is something between 2 and 6:

var num = 5
switch num {
// including 2,3,4,5,6
case 2...6:print("num is between 2 and 6")
default:print("None of the above")
}

You can use tuples in switch statements. You can use the underscore character (_) to tell Swift to “match everything.” You can also check for ranges in tuples. Here’s how you could match a geographic location:

var geo = (2,4)
switch geo {
//(anything, 5)
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,_):print("It's (1 or 2 or 3, Something)")
case (1...3,3...6):print("This would have matched but Swift already found a match")
default:print("It's something else")
}

In the first case, you are first trying to find a tuple whose first number is anything and whose second number is 5. 

The underscore means “anything,” and the second number must be 5. Our tuple is 2,4 so that won’t work because the second number in our tuple is 4.

In the second case, you are looking for the opposite of the first case

In this instance the first number must be 5 and the second number can be anything.

In the third case, you are looking for any number in the range 1 to 3, including 3, and the second number can be anything. Matching this case causes the switch to exit. 

We can use ranges to check numbers in switch statements, which makes them even more powerful.

The next case would also match, but because Swift has already found a match, it never executes. In this case we are checking two ranges.

Switch statements in Swift break on their own. 

If you’ve ever programmed in any other common language, you know you have to write break so that the case will stop. 

If you want that typical Objective-C, JavaScript functionality that will not use break by default (where the third case and fourth case will match), you can add the keyword fallthrough to the case, and the case will not break:

var geo = (2,4)
switch geo {
//(anything, 5)
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,_):
    print("It's (1 or 2 or 3, Something)")
    fallthrough
case (1...3,3...6):
    print("We will match here too!")
default:print("It's something else")
}

Now the third case and fourth case match, and you get both print statements:

It's (1 or 2 or 3, Something)
We will match here too!

Remember the value binding example from earlier? You can use this same idea in switch statements. 

Sometimes it’s necessary to grab values from the tuple. You can even add in a where statement to make sure you get exactly what you want. 

Here is the kitchen-sink example of switch statements:

var geo = (2,4)
switch geo {
case (_,5):print("It's (Something,5)")
case (5,_):print("It's (5,Something)")
case (1...3,let x):
    print("It's (1 or 2 or 3, \(x))")
case let (x,y):
    print("No match here for \(x) \(y)")
case let (x,y) where y == 4:
    print("Not gonna make it down here either for \(x) \(y)")
default:print("It's something else")
}

You might get a warning here telling you that a case will never be executed, and that is okay. 

This is the mother of all switch statements. Notice that the last two cases will never run. 

You can comment out the third and fourth switch statements to see each run. 

We talked about the first case and second case. The third case sets the variable x (to 4) to be passed into the print if there is a match. 

The only problem is that this works like the underscore by accepting everything. You can solve this with the where keyword. 

In the fourth case, you can declare both x and y at the same time by placing the let outside the tuple. 

Finally, in the last case, you want to make sure that you pass the variables into the statement, and you want y to be equal to 4. You control this with the where keyword.

Stop...Hammer Time

It’s important to have some control over your switch statements and loops. You can use breakcontinue, and labels to provide more control.

Using break

Using break stops any kind of loop (forfor in, or while) from carrying on. 

Say that you’ve found what you were looking for, and you no longer need to waste time or resources looping through whatever items remain. Here’s what you can do:

var mystery = 5
for i in 1...8 {
    if i == mystery {
        break
    }
    print(i) // Will be 1, 2, 3, 4
}

The loop will never print 5 and will never loop through 6, 7, or 8.

Using continue

Much like breakcontinue will skip to the next loop and not execute any code below the continue

If you start with the preceding example and switch out break with continue, you will get a result of 1, 2, 3, 4, 6, 7, and 8:

var mystery = 5
for i in 1...8 {
    if i == mystery {
        continue
    }
    print(i) // Will be 1, 2, 3, 4, 6, 7, 8
}

Using Labeled Statements

break and continue are fantastic for controlling flow, but what if you had a switch statement inside a for in loop? 

You want to break the for loop from inside the switch statement, but you can’t because the break you write applies to the switch statement and not the loop. 

In this case, you can label the for loop so that you can tell the for loop to break and make sure that the switch statement does not break:

var mystery = 5
rangeLoop: for i in 1...8 {
    switch i {
    case mystery:
        print("The mystery number was \(i)")
        break rangeLoop
    case 3:
        print("was three. You have not hit the mystery number yet.")
    default:
        print("was some other number \(i)")
    }
}

Here, you can refer to the right loop or switch to break. You could also break for loops within for loops without returning a whole function. The possibilities are endless.

--------------------------------------------------------------------------------------------------------------------------------------------------------



Summary

This chapter has covered a lot of ground. You can see that Swift isn’t another version of Objective-C. 

Swift is a mixture of principles from a lot of languages, and it really is the best of many languages. 

It has ranges, which pull syntax straight out of Ruby. It has for in loops with enumerate and tuples, which both are straight out of Python. 

It has regular for loops with i++ or ++i, which come from C and many other languages. It also has optionals, which are Swift’s own invention.

You’ll see shortly that Swift has a lot of cool features that make it easy to use along with your Objective-C and C code. You have already gotten a small taste of arrays. 

Chapter 2, “Collecting Your Data: Arrays and Dictionaries,” covers arrays and dictionaries in detail. You’ll see how Swift’s strong typing and optionals come into play.

--------------------------------------------------------------------------------------------------------------------------------------------------------

Go to pearson website


Learn more...

https://itexamtools.com/master-of-applied-data-science/

https://itexamtools.com/what-is-the-difference-between-python-and-ruby/

https://itexamtools.com/7-skills-employers-of-the-future-will-be-looking-for/

https://itexamtools.com/aws-masterclass-go-serverless-with-aws-lambda-aws-aurora/

https://itexamtools.com/azure-fundamentals-how-to-pass-the-az-900-exam/

https://itexamtools.com/what-is-a-business-intelligence-dashboard/

 https://itexamtools.com/affiliate-bots-v2-07/

https://itexamtools.com/online-social-media-jobs-product-review/

https://itexamtools.com/recession-free-profits-product-review/

 https://itexamtools.com/niche-marketing-kit-product-review/

 https://itexamtools.com/click-wealth-system-product-review/

 https://itexamtools.com/livpure-product-review/

 https://itexamtools.com/ikaria-lean-belly-juice-product-review/






























































































































































Comments