Lesson 1 - Basic Swift
Notes Taken by Will Oakley & Shubham Gupta
Variables
Swift has two types of basic containers for data. Variables (denoted by the var
keyword) can contain mutable data, meaning that it can change over the course of your program’s runtime. Constants (denoted by the let
keyword) are set upon initialization and cannot be changed once they are set.
Variables types in swift are inferred. This means that it is not required to assign a type, as you have to in languages like C or Java. For example if you declare a variable like this:
var aNumber = 100
aNumber
will forever be of type Int.
Optionals
Optionals (denoted with a ?) are a special type of variable in Swift. Normally, variables cannot be assigned to nil. Optionals allow this to happen. For example if we declare some variables like this:
var aFloat: Float?
var aDouble: Double!
aFloat
can contain nil
while aDouble
must keep a value once it is assigned.
Optionals can be “force unwrapped” (the value will be “force read”) by adding a !.
Note: Xcode will frequently propose unwrapping an optional to fix a variety of common issues. This is usually not the best way to fix a problem!! Make sure you consider what is causing an error before you use Xcode’s auto-solver.
We can avoid these force unwrap issues by using something like an if let
statement. The structure is as follows:
var optionalName: String? = "John Appleseed"
if let name = optionalName {
print("Hello, \(name)")
}
In this example, “Hello, John Appleseed” will only be printed if optionalName
is not null. In this case, it is assigned to “John Appleseed,” so therefore it will be printed. If we were to assign optionalName
to nil
, nothing will be printed and the program continue on without crashing.
Functions
Functions in Swift are structured in a very clear format. A basic function signature will follow the structure as follows:
func lookAtThis(number: Int) -> String
This is a function called “lookAtThis” with a single argument “number” of type Int
. It will return a variable of type String
.
Functions can have as many arguments as you would like. Usually the argument label is required when you call the function unless you prefix it with an _ when it is declared.
Arrays & Dictionaries
Arrays syntax in swift is very similar to other languages. An array of numbers could be declared like this:
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
Again, similarly to other programming languages, the syntax for accessing elements of the array is very simple. Just use something like oddNumbers[2]
to get the 3rd element in the array (in this case that would be 5).
Dictionaries are ways of storing data indexed by string keys. They are declared like this:
var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
"triangular": [1, 3, 6, 10, 15, 21, 28],
"hexagonal": [1, 6, 15, 28, 45, 66, 91]]
If we wanted to access the array “primes”, we would use the statement interestingNumbers["primes"]
, because the “primes” array is stored under the key “primes”.
Control
While statements are the same as any other programming language. They are used as such:
while aBoolean{
// do something
}
This while loop will continuously run until aBoolean
becomes false.
For loops take on a slightly unique syntax in Swift. An example for loop is as follows:
for uni in universities{
//do something with uni
}
This for loop will iterate over every element in the list universities
.
Lets say we want to iterate over a range of numbers instead. We would this syntax to do so:
for n in 1...5 {
print(n)
}
This will print out 1 2 3 4 5
. Note that this is inclusive of the number 5
. If we want to iterate up to, but not including 5, we would write it as below:
for n in 1..<5 {
print(n)
}
This will print out 1 2 3 4
.
Extensions
Extensions are used to add new functionality to an existing class, structure, enumeration, or protocol type. Basically it allows you to “extend” the functionality of basic Swift types. This is also useful to clean up your code and modularize your project into smaller files.
extension String {
subscript (r: Range<Int> ) -> String {
*** YOUR CODE HERE ***
}
Doing so, we have extended the String class and added to its functionality.