Swift Basics


Variables, Constants, Types

constants → let

variables → var

let duckName: String =”This is constant”
var duckAge: Int = 42
let countOfChars = duckName.count // = 100
let output = duckName + " has \\(countOfChars) has chars."
let longString = """
This is a string
that spans across
multiple lines.
"""

<aside>

All of the basic types in Swift - integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types

</aside>

Basic Operators

Comparison Operators

let tree = "Apple tree"
let isApple = tree == "Apple tree" // true
let isOrange = tree == "Orange tree" // false
let isGreater = tree < "Cherry tree" // true
let sameObject = tree === "Apple tree" // Error
//---------------IMPORTANT----------------- 
//String is a value type. You can only compare 
//reference types with the Identity operator

Range Operators

Range operators are shortcuts for expressing a range of values


Collection Types

Collections assigned to

  1. variables will be mutable
  2. constants will be immutable (size and content are fixed)

Arrays

let numbers: [Int] = [1,2,3,4]
numbers[1]=5 // [1,5,3,4]
numbers.insert[6, at: 2) // [1,5,6,3,4]
let removedItem = number.remove(at: 0) // [5,6,3,4]
// remove(at:) returns this item

Sets

let emails = Set<T>() //creates an empty set type T
let emails: Set<T> = []

Performing Set Operations • intersection(_ :) - creates a new set with only the values common to both sets • symmetricDifference(_ :) - creates a new set with values in either set, but not both • union(_ :) - creates a new set with all of the values in both sets • subtracting(_ :) - creates a new set with values not in the specified set • isSubset(of: ) - determines whether one set is a subset of another specified set

var emails: Set = ["a@cool.email", "an@other.email"]
emails.insert("new@cool.email")
emails.remove("an@other.email")
let validEmails: Set = ["new@cool.email"]
emails = emails.intersection(validEmails)
// 0: "new@cool.email"

Dictionaries

let userIdsAndEmails = [Int: String]()

var userIdsAndEmails=[1:"flo@", 2: "dora@"]
userIdsAndEmails[3] = "dominic@"
userIdsAndEmails[1] = "florianbodlee@"
userIdsAndEmails[2] = nil //Remove a key-value pair
userIdsAndEmails//[3:“dominic@",1:“florianbodlee@”]

Tuples

var person = ("Flo", 21)
person = ("Dora", 28)

let person = (name: "Flo", age: 22)
person.name //Flo
person.age //22

Control Flow

if-else

let age = 42
if age > 21 {
print("You are an adult")
} else {
print("You are not an adult")
}

switch

switch age {
case 42:
	print("The meaning of life")
default: //must be exhaustive. always last
	print("You are \\(age)")
}

Ternary Conditional Operator

let happy = true
let mood = happy ? "yes" : "no" //yes

Control Transfer Statements

While & for loop

Pattern Matching

Use the underscore character (_) (wildcard pattern), to match any value

let numbers = (42, 24)
switch numbers {
	case (0, 0):
		print("Both numbers are 0")
	case (_, 42), (42, _):
		print("Contains 42")
	case let (a, b) where a == b:
		print("Both numbers are \\(a)")
	default:
		print("Two numbers %")
}
let nums=[(0,0),(42,0),(21,42),(100,200)]
for case let (first, 0) in nums {
	print("2nd num:0 & 1st is: \\(first)")
}

Functions


Classes, Structs, Enums

Classes vs Structs

Stack Memory vs Heap Memory


Optionals

You use optionals in situations where a value may be absent → There is a value, and you can unwrap the optional to access that value. If not → nil

… Int? → tells that variable contains optional

Optionals Chaining

When you see ? after a variable and before a dot (.), you are performing Optional Chaining.