Introduction to Swift

Updated: Dec 2, 2020

In this guide, you will learn the fundamentals of the Swift programming language.


Variables and Constants

Constants refer to fixed values while Variables don't.


In Swift use let when you're defining a constant:

let numberOfEpisodes: Int = 17

And use var when you're defining variable:

var savingsBalance: Double = 493.7

If you provide an initial value for a constant or variable at the point it's defined then you don't need to use type annotations. For example:

let numberOfStudents = 12

Numbers in Swift

The two basic data types for variables are strings and numbers. Numbers can be integers (Int) or decimal numbers (Float or Double). When declaring a variable as a decimal number, you have to choose between Float and Double. The big difference between the two is that Float variables can only hold seven digits of precision while Double variables can hold twice that number.


There are several types of numbers you'll use in Swift and the most common are Int, Double, and Float. Integers are whole numbers with no fractional component:

let age: Int = 12

Doubles and Floats can have a fractional component:

var savingsBalance: Double = 493.7

Now you might wonder what's the difference between Float and Double and which you should use? It's easy. The biggest difference between those two types is precision how many digits they can hold. So, many people suggest using Double because you will avoid needing to convert Float variables to Double or vice versa. Use Float only if you want to save memory but that's a rare case


Strings

Strings represent a series of characters:

let myName: String = "Gustas"

Booleans

Boolean can only ever be true or false:

let silentMode: Bool = false

Optionals

It's very important to understand Optionals because it's meant to improve the safety of Swift code.


If you define an optional variable without providing a default value then the variable is automatically set to nil.


You need to unwrap optionals to safely use them


Optionals are declared with a question mark ? right after a variable type:

var artistName: String?

If you want to access the value of an optional variable or constant, you'll need to unwrap it:


With force unwrapping, using !


With optional binding, using if let


With implicitly unwrapped optionals, using !


Rule number one is that you should never force unwrap an optional that's nil unless you're certain that the optional you're unwrapping is not nil. So the question now is how to unwrap the optional safely? Take a look at this example:

if artistName != nil {
 print(artistName!)
}

As you can see we're using conditional expression to avoid our app from crashing.


Now let's see how to use optional binding instead of force unwrapping the optionals:

let artistName: String? = "Drake"
if let artistName = artistName {
	print(artistName)
}

In this example, we use optional binding to assign the value of optionalArtistName to the constant artistName if it's not nil. The biggest difference between force unwrapping and optional binding is that it's impossible to accidentally unwrap an optional that's nil.


Another useful tip is to use a guard statement in Swift to return a function when a condition isn't met.

func icon() -> {
     guard let image = UIImage(named: "Photo") else {
       	return UIImage(named: "Default")!
     }
 
     return image
}

In the above example, we check if we have image named "Photo". Then if it's not nil we assign that image to the constant image. And finally, if the expression is nil, the else clause of the guard is invoked and we return UIImage named "Default" and exit the function.


Now let's talk about implicitly unwrapped optionals. Implicitly unwrapping that optional means that it's still optional and might be nil, but Swift eliminates the need for unwrapping. But the problem is that you can't catch the error using implicitly unwrapped optionals Those optionals require you to be absolutely sure there's a value there before you use them.


Arrays

Arrays store a list of values:

var myGrades: [Int] = [4, 5, 9]

You can add a new grade to your array:

myGrades.append(10)

To check how many grades there are in the array:

let count = myGrades.count

And to print first grade from our array use index:

print(myGrades[0])

Creating an Empty Array:

var myGrades = [Int]()

Dictionaries

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key that acts as an identifier for that value within the dictionary.

var airports: [String: String] = ["JFK" : "John F. Kennedy International Airport", "LAX" : "Los Angeles International Airport "]
if let airportName = airports["JFK"] {
 print("We're going to land at \(airportName)")
}

To add a new airport to the dictionary it's very simple using the following syntax:

airports["VNO"] = "Vilnius International Airport"

Functions

Functions in Swift are quite similar to functions in other programming languages. Take a look at the example below how Function can be created:


func addTwoInts(a: Int, b: Int) -> Int {
 return a + b
}



40 views