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:


No comments: