Poppy
0
Q:

extension swift

extension Example {
  // code here for the Example type...
}
6
// 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 {
        return getA() + amount
    }
}

var mc = MyClass()

print(mc.getA()) // Direct part of class (Output: 5)
print(mc.add(5)) // Function from extension - called as if the fucntion were in the original definition (Output: 10)
1

New to Communities?

Join the community