Saturday, November 19, 2016

Swift Tip - Extensions

Extensions allow you to extend the functionality of an existing class, structure, enumeration, or protocol.  Here is an useful example:

extension Int {
    var isPerfectSquare:Bool {
        let sr = sqrt(Double(self))
        return ((Int(sr) * Int(sr)) == self)
    }

}

The above isPerfectSquare() function extends the Int class. You can call it to check if a number is a perfect square, like this:

        print(25.isPerfectSquare//---true---
        print(26.isPerfectSquare//---false---
        print(27.isPerfectSquare//---false---
        print(36.isPerfectSquare//---true---

No comments: