Contents

Swift Cheatsheet

Contents

Basics

  1. Data Types
1
2
3
4
 let intVar : Int = 10
 let doubleVar : Double = 10.5
 let boolVar : Bool = true
 let stringVar : String = "Hello, World!"
  1. Conditional Statements
1
2
3
4
5
if boolVar {
   print("It is True!")
} else{
   print("It is False!")
   }
  1. Loops
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
   //for loops:
   for i in range 1...5 {
       print(i)
   }
   //while loops:
   i = 0
   while i < 5 {
       print(i)
       i += 1
   }
  1. Use let for constants and var for variable (Using let is always a good idea)

  2. Functions

1
2
3
4
    // like go, first comes with variable name,then comes after with data type
    func add(a Int,b Int) -> Int {
        return a + b;
    }

OOP

  1. Constructor or Initializer:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    class Car: Vehicle {
        var color: String
    
        init(wheels: Int,color: String) {
            self.color = color
            super.init(wheels: wheels)
        }
    
        convenience init() {
            self.init(wheels: 4, color: "Red")
        }
    }
    
    let myCar = car() // use convenience init
    
  2. Protocols (similar to interface in Java)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    protocol Runnable {
        func run()
    }
    
    class Human: Runnable {
        func run() {
        print("Human runs on two legs")
        }
    }
    
    class Cheetah: Runnable {
        func run() {
        print("Cheetah runs very fast!")
        }
    }
    
  3. Extensions

    1
    2
    3
    4
    5
    6
    7
    
    extension Int {
     var squared: Int {
         return self * self
         }
     }
    
    let fourSquared = 4.squared  // Outputs: 16