1 - Introduction to Swift: Part 1
Woo! First post. This course is designed to be easy to understand by all those willing to code and create. Whether or not you are someone who has never programmed before to those who are advanced and need a refresher. Let’s get right to it.
According to Wikipedia, Swift is a “general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. for iOS, macOS, watchOS, tvOS, and Linux.” Ok, well that probably makes no sense to most non-programmers. In my eyes, a programming language is a way to take ideas and logic and communicate those things to a computer in order to solve problems. Perhaps I had a really long list of names and I needed to sort them alphabetically. That sort of problem can be more easily solved by explaining to a computer how to perform that operation instead of manually doing the task myself.
There are a ton of languages, and each one has advantages and disadvantages depending on the task we want to perform. We are going to be messing with Swift because it interacts with the Cocoa Touch Interface (which allows us to make iPhone applications). Wooo!
Downloading Xcode
Xcode is a program created by Apple for developers to create applications for Mac, iPhone, iPad, and other Apple architectures. It is called an IDE, which stands for Integrated Development Environment. In order to program in swift, we are going to download it. Assuming that you are already using a Macintosh computer, download the following application:
Okeydokey after you have that downloaded, load it on up. We are going to be learning the basics of the Swift programming language, and what better way to play with new tech than in a playground. Go to File > New > Playground.
You’ll see a pop up window asking you to name your playground file, and select iOS as the platform. Click next to save the file (I suggest making a folder on your desktop to keep all of your practice projects organized). Save it and viola, you have a Swift Playground File with the following code:
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
Ok so if you’re already confused, don’t panic. The few lines that your looking at aren’t very important at the moment. Keep them at the top of the file and we’ll come back to them. As you can see there are different parts of the developer window:
The portion where the code exists is the source editor. That’s where you can edit your code.
On the right side is the results sidebar. When you do calculations, the playground file will automatically evaluate expressions and present them. You’ll see that in action soon.
On the top bar are the activity viewer and the panel controls. You can mess around with the different buttons to see what they do, but for now we’ll keep it at the default settings.
We are going to start at the bottom level, comments.
Comments
Comments are simply notes put into a program by a developer in order to keep track of what is going on and document the functionality of their code. They are important in case you have a very complex project and need to remember what parts are dedicated to what functionality. We can make comments in swift by using double back slashes [//]!
// This is a comment!
Easy as that. Woo! We can also make comments over several lines
// This is the first line of a comment
// This is the second line!
// OMG a third line?!
Say that we want to write a paragraph that lasts over a ton of lines. It would be annoying to keep making double slashes on every line. We can use another method of multiline comments.
/* If we put a slash (/) and an asterisk on the inside
then we can write a comment over several lines
without worrying about putting double slashes on every line.
We end it by putting another asterisk on the inside followed by
another slash, kind of like book-ends */
Comments are as simple as that. Let’s move on to some math.
Math
Math is easy as pi, pun intended. Take a look at the following code to see different operations:
// Addition
2 + 2
// Subtraction
8 - 4
// Multiplication
1 * 4
// Division
24 / 6
As you write these lines, the results sidebar should start showing the evaluations of each of the expressions!
The different symbols that create the operations (+, -, /, *) are called operators. Makes sense. Here’s an operator that may be foreign to some:
14 % 10
This operator determines the remainder after a the first number is divided by the second number, it’s called modulus. 10 goes into 14 one time, leaving 4 behind all lonely, but that’s ok because that’s our answer.
On top of these basic operators we can also perform order of operations (remember PEMDAS?!? woo good times). Check out a few examples:
(10 / 2) - 1
24 % (5 * 4)
(10 * 15) - (((200 / 4) * 2) + 46)
All of these operations should evaluate to 4, asumming that our results pane is not lying. There are a bunch of other cool math functions that we can perform if we like:
// Trigonometric functions
sin(45 * Double.pi / 180)
cos(135 * Double.pi / 180)
// Exponential (Powers)
pow(2, 2)
// Square Root
sqrt(16)
// Min and Max (Determining which of the values is smaller/larger)
max(2, 4)
min(2, 4)
For the most part we have been dealing with whole numbers, which is great and all, but in real life we are going to be dealing with many different types of numbers. In most programming languages there are at least 3 different types of numbers:
- Integers: [Keyword: Int] Whole Numbers (i.e. 1, 8, 200, etc)
- Doubles: [Keyword: Double] Decimal Numbers (i.e. .012, 5.26, 98223.23, etc)
- Floats: [Keyword: Float] Pretty much the same thing as double, except for the way that the value is stored precision-wise. We can talk more about that later.
You’ll see more applications of different number types in a few moments, along with some other data types.
Constants
Now that we have gone over basic math, let’s talk about constants. Constants are pretty self explanatory, they are representations of values that will never change, thus they will stay constant. Pi is a constant at 3.14… (that’s as far as I remember). My favorite number is also a constant because it will never change! A large aspect of programming is being able to store values in constants that you can use later. Here’s how you do it.
// Constants
let myFavoriteNumber: Int = 8
Let’s break this down:
- Use the let keyword to declare that you want to make a constant
- Come up with a name for your constant.
- You need to place a colon at the end of your name, followed by what datatype you want the constant to be. In this case, my favorite number is a whole number, thus I want to store the value as an Integer (Int).
- Save a value to your constant.
You have now created your first constant. Now you can use the name of the constant in code:
myFavoriteNumber + 10 // will evaluate to 18
Constants are an important part of programming in that they can store values that are used multiple times throughout a program. If the developer realizes that they want to tweak the value of the constant they created, they only need to change one part of the code instead of every place they wanted to use the constant.
When I say “change the constant,” I’m referring to changing the value that we first instatiated the constant as. We would have to change the line of code where we first set myFavoriteNumber to 8. But What if we wanted to change the value of the constant half way through a program?
This will cause an error:
myFavoriteNumber = 10
We can’t just decide later on that we want to change a constant, that’s the breauty of it being a constant (it doesn’t change). If you wanted to save values that could change over time, then let’s talk about variables.
Variables
If you remember algebra at all, we are always trying to find x and y because for some reason they are lost all the time (lol I’m not funny). Variables in code are ways of storing information in memory so we can use them later, usually by using key words. Examples are better than explanation so:
// Variables
var accountBalance: Int = 8
This is very similar to our instatiation of a constant, except we use the var keyword. Now since this value is a variable, we can change it as we like. Say I have 200 dollars into my account instead:
accountBalance = 200
This does not throw an error! We can reassign the value of an variable as much as we want. We can even be more exact about it, say I deposit 500 dollars:
accountBalance = accountBalance + 500
This takes the current value of my account balance (which was 200), adds 500 to it, and then stores that value (700) back in my accountBalance variable.
There are many Increment and decrement operators that can shorten the line of code above:
// Increment and Decrement Operators
var counter: Int = 0
counter += 1 // Performs counter + 1; Value of counter is now 1
counter -=1 // Performs counter - 1; Value of counter is now 0
counter = 10 // Sets counter to = 10; Value of counter is now 10
counter *= 3 // Performs counter * 3; Value of counter is now 30
counter /= 3 // Performs counter / 3; Value of counter is now 10
counter %= 4 // Performs counter % 4; Value of counter is now 2
Here’s a future warning for ya, don’t do this:
var myFavoriteInteger: Int = 8
var myFavoriteDouble: Double = 10
myFavoriteInteger + myFavoriteDouble
This above code will throw an error. Why? Well it’s because we are trying to perform mathamatical operations that combine the use of an Int and a Double. You could perform the operation if you perform what is called a cast:
// We can cast the integer to be a double
Double(myFavoriteInteger) + myFavoriteDouble
// Or we can cast the double to be an integer
myFavoriteInteger + Int(myFavoriteDouble)
Ok that’s enough of numbers, we have two more datatypes to go until the end of this lesson:
Strings
Strings are simply characters combined to make words and other uniheximal symbols. The following is a string:
"Hello, World!"
Strings are surrounded with quotations! You can even perform the + operator to append two strings together:
"Hello" + "," + " " + "World!" // This creates the same string as above
Here’s how to create a string constant and variable:
let constantString: String = "This is a constant"
var variableString: String = "This is a variable"
What if I had an integer variable and I wanted to create a string variable that used the integer in the string? For example, let’s say I want to create a string “My favorite number is |number|” and I needed to put my variable value in place of the number. We use a method called interpolation:
// Here is my favorite number stored in a variable
var myFavoriteNumber: Int = 8
// Now here is the string that uses my favorite number
var myFavoriteNumberString: String = "Josh's favorite number is \(myFavoriteNumber)!"
Booleans
This is the last datatype of this lesson. Booleans refer to true or false values. Simple:
// this is true
true
// this is false
false
// this is a constant created to mean true
let yes: Bool = true
// this is a constant created to mean false
let no: Bool = false
This is a very important datatype for future programming concepts. There are boolean operators provide comparisons of numbers, strings, and even booleans themselves:
// x == y means x is equal to y
1 == 1 // true
1 == 2 // false
"Hello" == "Hello" // true
"Hello" == "Hello!!" // false
// x != y means x is not equal to y
1 != 2 // true
1 != 1 // false
// x > y means x is greater than y
1 > 2 // false
2 > 1 // true
// < (less than)
1 < 2 // true
2 < 1 // false
// >= (greater than or equal to)
1 >= 2 // false
1 >= 1 // true
2 >= 1 // true
// <= (less than or equal to)
1 <= 2 // true
// AND: x && y means that both x and y have to be true in order to be true, else false
true && true // true
true && false // false
// OR: x || y means that either x or y have to be true in order to be true, else false
true || false // true
false || false // false
Ok so that was a ton for the first lesson, but the basics are necessary if we are going to dive into complicated iPhone application programming. Check out the next lesson where we will go over another chapter of Swift Basics (conditionals, encapsulating variables, optionals, loops, and enumerations).