Swiftly

Swift 5.7 references for busy coders

Swift 5.6 cheatsheet

Constants

let myInt = 5
let myString = "Five"

Variables

var myInt = 5
myInt = myInt + 5

Type annotations

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

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 myInt = myInt {
  print("myInt is \(myInt)")
}
// Output: "myInt is 5"

Enum

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

Switch statement

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

Declaring a function

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

Calling a function

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

Declaring a struct

struct Player {
  let name: String
  var score: Int
  mutating func doubleScore() {
    score *= 2
  }
}

Instantiating a struct

var sam = Player(name: "Sam", score: 5)
sam.doubleScore()
print("\(sam.name)'s score: \(sam.score)")
// Output: "Sam's score: 10"

Array

var myArr = [10, 20]
myArr.append(30)

Loop over array

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