swift class extension code example

Example 1: create extension swift

extension Example {
  // code here for the Example type...
}

Example 2: extension swift

// A basic class
class MyClass {
    private let a = 5

    func getA() -> Int {
        return self.a
    } 
}

// An extension of that class - adds a function
extension MyClass {
    // Add an amount to the value of `a`
    func add(_ amount: Int) -> Int {
      	// self can be used to access MyClass' members
        return self.getA() + amount
    }
}

var mc = MyClass()

print(mc.getA()) // Direct member of the class (Output: 5)

// Function from extension - called as if the function 
// was in the original definition. (Output: 10)
print(mc.add(5))