Class Extensions

Swift allows developers to add functionality to existing classes (and also structs, enums and protocols). This can be particularly useful if we do not have access to the source code. Even better, the ability to create extensions applies to all classes, including those in the Swift standard library.

If you have previously created any sort of 'Utility' class with class (static) functions, then some of them may be good candidates for extension methods. Consider the example below:

class StringUtils {
    
   class func reverse(string: String) -> String{        
       return String(string.reversed())
    }
}

var greeting = "Hello"
var reversedGreeting = StringUtils.reverse(greeting) //"olleH"

In order to reverse the string we need to call a method on the StringUtils class, it would be advantageous if we could simply call reverse on the greeting. Extensions methods allow us to do that - so we can extend String as follows:

extension String {
    func reverse() -> String{
        return String(self.reversed())
    }
}

var greeting = "Hello"
var reversedGreeting = greeting.reverse() //"olleH"

Whilst extensions allow us to create methods, we cannot create stored properties (Computed properties are fine however)

Tasks

  1. Extend Int with a function to return the square of its value
  2. Extend String with a function to create an acronym from a sentence
  3. Extend String with a function to count any given character in that string