Answers for "how are swift extensions implemented"

3

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))
Posted by: Guest on August-10-2020

Code answers related to "how are swift extensions implemented"

Code answers related to "Swift"

Browse Popular Code Answers by Language