Chapter 2: Intro to Swift

Apple has always been on the cusp of new technologies. When they released Swift, (some of) the world cheered. πŸŽ‰


What you will learn

  • What is Swift?
  • What makes Swift different
  • The future of Swift
  • Variables
  • Constants
  • Types
  • Collection Types
  • Control Flow
  • Conditionals
  • Functions

Key Terms

  • Syntax: the specific structure and order of a programming language.
  • Safe: a characteristic of Swift which means that it is less prone to syntax errors or other compile-time errors.
  • Fast: a characteristic of Swift which means that it is performs quickly and is efficient in nature.
  • Expressive: a characteristic of Swift which means that it's syntax is easily readable.

Swift is Apple's baby. According to Swift.org:

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

If you don't come from a computer science or programming background you may be thinking, "That's neat. BUT WHAT DOES IT MEAN? πŸ€”" Trust us when we say that it means that your learning-to-code life will be much easier than it could be.

Swift is an excellent first programming language to learn as it's syntax is generally easy to follow. There are also a ton of resources online (i.e. tutorials, YouTube videos, blogs, forums, etc.) to help you learn Swift.

Swift Foundations

Variables

Every programming language uses variables. They are like a container which allows you store data of many different types.

To declare a variable you must use the keyword var:

var message: String = "Hello, World!"

What we've just written tells our computer that we want to create a container (variable) with the name message of type String which contains the text "Hello, World!"

Something amazing about Swift is that it includes a feature called Type Inference. This means that Swift can analyze the data inside a variable is (text, number, true/false, etc.) and infer it's type.

To test this, simply remove String after declaring the variable message:

var message = "Hello, World!" //Type-Inferred String

As you can see above, we never explicitly told our computer that we wanted message to be a String but because of the quotes around Hello, World!, Swift can infer it's type.

Variables are called variables because, well, they are variable – their value can be changed.

For example, if we wanted to change the value of our message variable we would need to write the name of our variable and change it's value like so:

var message = "Hello, World!"
message = "Hello, Swift!"

Now message is equal to "Hello, Swift!".

Constants

Sometimes, there are values where you don't want a certain value to ever change. A date like your birthday, the version number of your application, or the name of your hometown for instance.

In Swift, we call these values constants.

To declare a constant, you must use the keyword let.

If we were to change the keyword var to the keyword let in our example above we would be presented with an error because we cannot modify a constant.

let greeting = "Hello, World!"
greeting = "Hello, Swift!" // Error

Types

String

So far, in the code above we've only referred to values of type String. A String can be used to hold textual data.

Strings are also powerful in how they can be modified or even convert and hold other types of values.

For example we can use String Concatenation to combine several String values together using the + operator.

let album = "Nevermind"
let artist = "Nirvana"
let review = " is amazing! πŸ™Œ"
let description = "The album " album + " by " + artist + review

//description = "The album Nevermind by Nirvana is amazing! πŸ™Œ"

Another neat thing we can do is use String Interpolation to encapsulate other variables and pass them into a String value when we want.

let birthday = "May 15, 1992"

let bio = "My birthday is \(birthday)."

// bio = "My birthday is May 15, 1992."

You can even pass in values that are not of type String and Swift can convert them.

Int

The keyword Int is short for Integer. In math, an integer is most basically defined as a whole number.

We can use an Int value in a variable or a constant:

var age: Int = 24 // Explicitly declared Int
var salary = 70000 // Type-inferred Int
let birthYear = 1992
let daysInAYear = 365

Bool

The keyword Bool is short for Boolean. Booleans are simply true and false values. Just like all the above types, you can explicitly declare a variable of type Bool or let Swift infer it's type by setting the value of a variable to be either true or false.

var isFinishedLoading = true // Type-inferred
var dataLoaded: Bool = false // Explicit

Double / Float

A Double is a number value similar to the type beneath it – Float. The difference between the two is how precise you can be.

A Double is a 64-bit floating point number value which can be as precise as 15 decimal digits.

A Float is a 32-bit floating point number value which can be precise to 6 decimal places.

As you can see, a Double is more precise than a Float.

var intersectVersion = 2.0  // Type-inferred Double

Something to note: Swift defaults to type-infer decimal values as a Double, not Float. To declare a variable of type Float, be explicit:

var intersectVersion: Float = 2.0

Most of the time, you will be using Double values in Swift (and in this book).

Collection Types

In Swift, there are two different ways to store collections of values – Array and Dictionary.

Array

An array is a collection of values which are organized by index. The index is the count of how many objects there are inside of the array. In Swift, zero-indexing is used meaning that the first item in the array actually has an index of 0. From then on, the number increases by one.

Defining an Array

Arrays are always written inside of brackets. Each value is separated by a comma.

var unoCards: [String] = ["Skip", "Wild", "Wild + Draw Four"] // Explicitly-declared Array of Strings

var unoCards = ["Skip", "Wild", "Wild + Draw Four"] // Type-inferred as [String]

Arrays can contain values of a single type like the one above, but you also can include multiple types in an array.

To get the value for a single item from our array, we need to do the following:

...

print(unoCards[0]) // Prints

Using print, we can print the value of the first item (at index 0) in our unoCards array – "Skip".

Modifying an Array

I am going to create an array with a grocery list.

var groceryList = ["Milk", "Eggs", "Cheese"]

To add an item to our list, we simple use the .append() function in Swift:

var groceryList = ["Milk", "Eggs", "Cheese"]

groceryList.append("Marshmallows")

//groceryList = ["Milk", "Eggs", "Cheese", "Marshmallows"]

This will add the value "Marshmallows" to the end our groceryList array.

To add multiple items to our array, we can use the .extend([]) function in Swift:

var groceryList = ["Milk", "Eggs", "Cheese"]

groceryList.append("Marshmallows")

groceryList.extend(["Oreos", "Quinoa"])

//groceryList = ["Milk", "Eggs", "Cheese", "Marshmallows", "Oreos", "Quinoa"]

To insert an item at a certain point in an array, use the .insert(_:atIndex:) function in Swift:

var groceryList = ["Milk", "Eggs", "Cheese"]

groceryList.append("Marshmallows")

groceryList.extend(["Oreos", "Quinoa"])

groceryList.insert("Potatoes", atIndex: 2)

//groceryList = ["Milk", "Eggs", "Potatoes", "Cheese", "Marshmallows", "Oreos", "Quinoa"]

The value "Potatoes" get added and has an index of 2. Remember, that Swift uses zero-indexing.

To change a single item in an array, subscript the item you want to change and give it a shiny new value.

...

groceryList[0] = "Bread"

//groceryList = ["Bread", "Eggs", "Potatoes", "Cheese", "Marshmallows", "Oreos", "Quinoa"]

Dictionary

A Dictionary allows you to store data in pairs containing a key and a value. Just like a dictionary in a spoken/written language, each word has a definition. Comparing the two, in a Swift Dictionary, the key = word and the value = definition.

Look at the dictionary I have declared below:

var screenSizeInInches = ["iPhone 7" : 4.7, "iPhone 7 Plus" : 5.5, "iPad Pro" : 12.9]

To access the value of an item in a Dictionary, you could do the following:

print(screenSizeInInches["iPhone 7"]) // Prints 4.7

Notice how I called the Dictionary, then inside of the brackets subscript, I included the String value for the key? After putting that inside the print function, it prints the value.

Modifying a Dictionary

Now, I want to add an iPad Air 2 to my array of screen sizes. To do this, we need to type the name of our array, add brackets as a subscript, and add a value inside the brackets to add the key. To add the value, we add an equals sign (=) and set the value we want.

screenSizeInInches["iPad Air 2"] = 9.7

//screenSizeInInches = ["iPhone 7" : 4.7, "iPhone 7 Plus" : 5.5, "iPad Pro" : 12.9, "iPad Air 2" : 9.7]

Control Flow


Loops

There may be times where you'll want to loop through a collection of data and perform a certain task or do something while a certain condition is met.

There are 3 main loop types in Swift: while, repeat-while, and for-in.

The while loop

This, in my opinion, is the easiest loop to understand. It essentially states that while something is true, that it executes a block of code until it is false. Then it stops looping.

Here is an example:

var finished = false

while !finished {
    print("Loading...")
}

The code above means that while the variable finished is false, our code should print "Loading..." to the console. Note that the exclamation mark (!) before finished means the logical not and read as "not complete".

The repeat-while loop

The repeat-while loop operates very similarly to a regular while loop, with one key difference.

In a repeat-while loop, the code to be repeated is executed first, then the condition is checked to see whether or not the loop continues.

A while loop, the condition is checked first and that determines whether or not the code runs.

Here is an example:

var sum = 10

repeat {
    size = size + 1
} while size < 15

This loop will continue increasing the size by adding the value of size plus one until it reaches 15. The thing to remember here is that the condition is checked after the code loops.

There are opportunities where you need to run code before checking if a condition is met. The repeat-while loop is the way to make it happen.

The for-in loop

Another type of loop is for-in. It is used to iterate through a collection of data and perform an action to each item in that collection.

For example:

var unoCards = ["Skip", "Wild", "Wild + Draw Four"]

for unoCard in unoCards {
    print(unoCard)
}

The code above would iterate through each item in the unoCards array and print the name of each item until it reaches the end. Then, our loop terminates.

You also can loop through a range of values. In Swift, a range is denoted by two or three dots.

1...5 is an inclusive range of the numbers from 1 until 5. The three dots means that values will be 1, 2, 3, 4, and 5.

1..< 5 is a non-inclusive range of numbers from 1 until 4. The two dots and less-than sign indicates that the values considered will be 1, 2, 3, and 4.

Conditionals

If Statements

Sometimes you might want to create conditional code that only will execute under certain conditions. That is where the if statement becomes very useful.

Basically, they work like this: if x is true, then perform y.

For example:

let carModel = "Delorean"

if carModel == "Delorean" {
    print("Great Scott!")
} else if carModel == "Geo Metro" {
    print("It drives, right?")
} else {
    print("If it's got wheels and drives, it's a car!")
}

In the above statement, we've said that if the carModel is equal to "Delorean", that it should print a message to the console. If it is equal to "Geo Metro", it should print a message specific to that model. Finally, if it is neither a Delorean or a Geo Metro (thank goodness), then we should print a generic message.

The if statement combined with else if or else is frequently used.

If you have more than a few conditions to be met, then the next section will shed some light on what to do.

Switch Statements

The switch statement in Swift 3 is really useful for scenarios with multiple cases. Usually most decisions in code can be run through an "if/else" block, but for those that can't we can use a switch statement.

For example:

var unoCardValue = "Skip"

switch unoCardValue {
case "Skip":
    print("Skip") // "Skip" will be printed
case "Draw-Four":
    print("Draw-Four")
case "Reverse":
    print("Seven")
case "Wild":
    print("Wild")
default:
    print("No card selected!")
}

In the above example, we have set the value of unoCardValue to "Skip". We have created a switch statement and named it the same name as our variable.

Now when our value changes, it will be passed in to our switch statement and if it meets one of our 5 conditions, it will run the code written for that case.

When creating a switch statement, you must be exhaustive and write a case for every possible scenario. If you don't need or want to do that, you can declare a default case at the bottom of the switch statement to handle any case that is not one of the cases you have written. Since the only value we're checking is a String which could be anything, we need to declare a default case since there are endless possibilities outside of our defined cases.

Functions

In Swift 3, we can write functions which are like a set of directions or code that can be written once and used in multiple places.

Basic Function

To create the most basic function we need to use the keyword func and give it a descriptive name to describe what it does.

For example:

func printName() {
    print("Devslopes")
}

Function With Parameter

The function above is great and all, but what if we want to print a name other than Devslopes?

We can pass in a parameter so that it can say any name by naming a parameter and giving it a type within the parentheses of our function.

Like so:

func printName(name: String) {
    print(name)
}

Now when we call our function, we can pass in a String value with the parameter name containing any name we want!

Function With Parameter and Return Value

Sometimes, you want to perform a function and return a value to a variable of some kind. To do this, you simply add the return type you want to return and ask the function to return the relevant value.

Here's an example:

var fullName = buildName(firstName: "Caleb", lastName: "Stultz")

func buildName(firstName: String, lastName: String) -> String {
    return "\(firstName) \(lastName)"
    // Returns "Caleb Stultz" to our variable above.
}

The function above requires two parameters – firstName and lastName. When we pass in those values, we return a String to the variable fullName returning the full name.

Wrapping up

This chapter has been a flyover of the Swift 3 programming language. I hope you can see how great it is, just by looking at it briefly. If you're completely new to programming, don't worry. If this is confusing or overwhelming, you're not alone. But, the most important thing at this moment is that you push through, remember that truly anyone can learn to code, and that you need to compete against yourself at this point to get better.