Swift

Swift Extension Methods

I’m doing this code in the latest version of Xcode that is available as of this writing, Xcode 7 Beta 6. It does not work with Xcode 6 at all, because some of the features are only part of Swift 2.
Extension CordExtension methods are a language feature that allows you to add behavior to a class (“extend” that class’ functionality, if you will).

In .Net, extension methods are merely syntactic sugar. I previously talked about them here and here. I go into more detail in the links, but basically extension methods are implemented as new methods that take the “extended object” as a parameter. You might declare one something like this:

public static class StringExtensions
{
    public static bool StartsWithACapitalLetter(this string input)
    {
        return !string.IsNullOrEmpty(input) && Char.IsUpper(input[0]);
    }
}

Then, when I call “Pete”.StartsWithACapitalLetter() it returns true and “pete”.StartsWithACapitalLetter() returns false.

So, that’s .Net. What about Swift? In Swift, similar functionality can be achieved this way.

extension String {
    var StartsWithACapitalLetter:Bool {
        if (self.isEmpty) { return false }
        let firstCharacter = String(self.characters.first!)
        return firstCharacter == firstCharacter.uppercaseString
    }
}

As it stands, if I call “Pete”.StartsWithACapitalLetter I get true and “pete”.StartsWithACapitalLetter gives me false. Let’s break it down a little more.

The first thing you do is just use the Swift keyword extension in front of the name of the class you are extending. After that, you literally just “add code” to the class. In this case, I added a property (not a method) called StartsWithACapitalLetter that returns a boolean. Notice that within that method, I can use self just as if I had written this code inside of the original class itself.

That’s really all that there is to it.

Leave a Reply

Your email address will not be published. Required fields are marked *