iOS Ref

Swift 5 cheatsheet

This page has moved to swiftly.dev/cheatsheet! The archive below will not be updated.

Visit Swiftly for more Swift guides.

Constants

let myInt = 5
let myString = "5.5"

Variables

var myInt = 5
myInt = myInt + 5

Type annotations

let myInt: Int = 5
let myString: String = "5.5"

If statement

if 5 > 3 {
  print("5 is more than 3")
} else {
  print("5 is not more than 3")
}
// Output: "5 is more than 3"

Optionals

let myInt: Int? = 5
if let unwrappedInt = myInt {
  print("myInt is \(unwrappedInt)")
}
// Output: "myInt is 5"

Enum

enum CompassPoint {
  case north, south, east, west
}
var direction: CompassPoint = .north

Switch statement

switch direction {
case .north: print("Going north!")
case .south: print("Going south...")
default: print("Going east or west.")
}
// Output: "Going north!"

Function with param and return

func square(x: Int) -> Int {
  let squaredValue = x * x
  return squaredValue
}

Calling a function

let squareOf6 = square(x: 6)
print("Square of 6 is: \(squareOf6)")
// Output: "Square of 6 is: 36"

Declaring a struct

struct MyStruct {
  var myInt: Int
  let myStr: String
  mutating func squareMyInt() {
    myInt = myInt * myInt
  }
}

Instantiating a struct

var obj = MyStruct(myInt: 5,
                   myStr: "Hi! 👋")
obj.squareMyInt()
print("\(obj.myStr) \(obj.myInt)")
// Output: "Hi! 👋 25"

Array

var myArr = [1, 3]
myArr.append(5)

Loop over array

var sum = 0
for element in myArr {
  sum += element
}
print(sum)
// Output: "9"