Learning Swift and iOS Development Part 2: Intro to Swift
In the last post we learned how to install Xcode. In this post we are going to use Xcode to go over some of the basics of Swift at a high level.
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 (like this one!), YouTube videos, blogs, forums, etc.) to help you learn Swift.
This chapter serves as a precursor for the chapters to follow. It is mostly for your information and reference. We will dive in in detail later on. Let’s get started!
Fire up Xcode, and we are going to be working in something called a Playground. Simply open Xcode and select ‘Get started with a playground.’ Then select Blank.
Or from File > New > Playground
Name and save your Playground and then you should see something like this:
So what is this Playground? A Playground is an interactive work environment. We can code and immediately see the results of our code. This makes it a great tool for learning and experimenting. The code that you see in the rest of this post can be added into your Playground to follow along!
Swift Foundations
Variables
Every programming language uses variables. They are like a container which allow you to 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 (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 variable
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 you don’t want to ever change. A date like your birthday, or the name of your hometown for instance.
In Swift, we call this type of value a constant
.
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, converted, and even hold values of many different types.
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 series). Double
is the recommended number type.
Collection Types
In Swift, there are three different ways to store collections of values — Set
, Array
, and Dictionary
. For the purposes of this series, we will only be using and learning about the Array
and Dictionary
in Swift.
Array
An array is a collection of ordered values which are organized by index. The index is the location of the object 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 Stringsvar 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 "Skip"
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 .append(contentsOf:)
function in Swift:
var groceryList = ["Milk", "Eggs", "Cheese"]
groceryList.append("Marshmallows")groceryList.append(contentsOf: ["Oreos", "Quinoa"])//groceryList = ["Milk", "Eggs", "Cheese", "Marshmallows", "Oreos", "Quinoa"]
To insert an item at a certain point in an array, use the .insert(_:at:)
function in Swift:
var groceryList = ["Milk", "Eggs", "Cheese"]
groceryList.append("Marshmallows")groceryList.append(contentsOf: ["Oreos", "Quinoa"])groceryList.insert("Potatoes", at: 2)//groceryList = ["Milk", "Eggs", "Potatoes", "Cheese", "Marshmallows", "Oreos", "Quinoa"]
Dictionary
A Dictionary
allows you to store unordered 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. In a Dictionary
all the keys are the same type, and all the values are the same type.
Look at the dictionary I have declared below:
var screenSizeInInches = ["iPhone 7" : 4.7, "iPhone 7 Plus" : 5.5, "iPad Pro" : 12.9]
In the above dictionary this follows the pattern [key : value, key : value]
To retrieve the value for a given key you use subscript syntax like below:
print(screenSizeInInches["iPhone 7"]) // Prints 4.7
Notice how I called the Dictionary
, then inside of the brackets subscript, I included the key? After putting that inside the print
function, it prints the value. This will return an optional value, since it cannot be guaranteed that a requested key has a 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 num = 0
while num < 8 {
num += 1
print(num)
}// This will print out 1,2,3,4,5,6,7,8
In the above code, a condition is evaluated is num less than 8
. If that evaluates to true, the block of code is executed. In that block of code, we increment the num
variable by one, then print out the new incremented value. This continues until the num
value is incremented to the value of 9 at which point the condition evaluates to false, and the block of code is no longer executed.
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.
In awhile
loop, the condition is checked first and that determines whether or not the code runs.
Here is an example:
var size = 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. When we use ==
we are creating a check for equality, so we are saying if the value of the variable carModel
is the same as “Delorean” then evaluate to true and execute the block of code. We can use else if
to do additional checks.
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, however it can be a little messy.
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 is really useful for scenarios with multiple cases.
For example:
var unoCardValue = "Skip"switch unoCardValue {case "Skip":
print("Skip") // "Skip" will be printed
case "Draw-Four":
print(“Draw-Four”)
case "Reverse":
print("Reverse")
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 set the value to check equal to 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, we can write functions which are like a set of directions 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")
}printName() // this calls the function and will print out "Devslopes" to the console.
In the above example, we are declaring a function with the keyword func
giving the function a name printName
. The parentheses ()
are required after the name. And then what the function does when called is blocked within the curly braces { }
. Just because you have written a function though, doesn’t mean it does anything. We have to call
the function as shown in the above code snippet.
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 into the function. These are also referred to as arguments. These arguments can then be used inside of the function. The format looks like this:
func functionName(argumentName: argumentType) {
// code to execute can use argumentName as a variable.
}
Like so:
func printName(name: String) {
print("Hello, \(name)!")
}
Now when we call our function, we can pass in a String
value with the argument name
containing any name we want! Then when you call the function you will pass in your own string and it will execute the code using the parameter provided.
printName("JonnyB")
// this prints out "Hello, JonnyB!"
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. The syntax for returning a value is like this: -> ReturnType
for example -> String
or -> Int
.
Here’s an example. Let’s create a function that takes in as arguments a first and last name, combines that into a single String, and returns that value:
func buildName(firstName: String, lastName: String) -> String { return "\(firstName) \(lastName)" // Returns "Caleb Stultz" to our variable above.}var fullName = buildName(firstName: "Caleb", lastName: "Stultz")
The function above requires two parameters —firstName
and lastName
. When we pass in those values, we return a String
to the variable fullName
and set its value to 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.
In the next post we will take a bit of a deeper dive into variables. See ya there!
If you want to learn more about Swift and iOS development, head over to www.devslopes.com and enroll in our Apple Developer Slope where you’ll learn everything you need to know to develop iOS apps. ❤️