Software For the 21st Century


15 Nov

Swift Extensions

Written by Patrick Delaney
in Blog
Hits: 5558

Swift PlaygroundSwift Extensions....

Most languages have in-built functions that allow the developer to extract a subset of characters from a given string, for example the left x characters.  The Swift functions are a little convoluted for my liking - I'd like to build a set of helper methods to make this a little nicer to use.  What we will do is work with code to grab the left x characters from a string and develop that idea, ultimately we will have three methods to extract left, right and mid string information.  We will then take these methods and extend the native String datatype itself which should make life nice and easy going forward.


The Basic Solution

string left x

If you take a look at the above code we see an alphabet constant which holds the 26 letters of the alphabet (funny that!), what's far more interesting are the two bottom lines which do the actual work.  These two lines work together to grab the left 5 characters from the alphabet string.

The first line works out the character index of the last character we wish to extract, as in the character index of the letter f in this example.  We then simply pass this index to the substringToIndex method and grab the requisite number of characters - the second line of code.  Now, the obvious question is "What's this index thing about!  Can't I just pass the number of characters I want to substringToIndex?"  Well, Strings in Swift are Unicode compatible and although the perceived character may be one character it may have more than one Unicode scalar value under the hood, working out the character index gets us around any potential Unicode based problems. 

Making A Function

So we now have our basic code to work out the left most x characters, but I'm not interested in typing that every time I want to get that information!  So the code example below has wrapped our basic solution into a function that we can reuse whenever we want.

string left x func

As you can see, our function takes in two parameters, the string we're working on and the length we're trying to extract - once the function has worked out the extracted value it passes it back for use by the main block of code.  In order to use this function, all we have to do is call the left function as shown in the last line of code.  We can reuse this as often as we like - nice!  We could leave things here and be perfectly happy, but we can take things forward to another level and that is the whole point of this post!

Creating our String Extension

What we can do now is take our left function and add it to the native String datatype, in effect extending the base datatype to include our own custom code.

string left x ext1

The code example above shows that we've simply wrapped the function within an extension command.  So the very first line of code tells the compiler that we're extending the String class, we could be extending anything really.  We've had to make a couple of changes to the function to get this to work properly.

  1. We've removed the inString parameter.
    We no longer need it - the method is now part of the String class itself so we know what the string value is.
  2. Added references to self
    As we've removed the inString parameter, we use references to self in order to tell the method to use the current String object value

So now when we want to get the left(x) data from a string we have the left method available as part of the String class itself.  And what's really nice is that these methods now form part of the auto-complete mechanism.

And the final version...
I've taken the above and extended the String datatype further by including
 both right and mid methods to allow us to get that information nice and easily, I can see I'll be creating a Swift file of helper functions such as these.

string left x ext2

The right method is very similar to the left method except we're using the substringFromIndex method as opposed to substringToIndex.  The index value is calculated using the string's endIndex property and taking off the required length and passing that to substringFromIndex.

The mid function works with the substringWithRange method and we need to calculate two indexes to be able to use this, the start point and the end point for the string extraction.  Once we've calculated these indexes, a process you should be familiar with now, we pass them to the substringWithRange method by means of a 1/2 open range (..<).  Note the parameter labels in the method call (bottom line) - extension methods with more than one parameter force parameter labels for all parameters bar the first.  The reason the first isn't labelled by default is that Apple thinks the first parameter should be obvious when you look at the method name.  For readability I've forced the first parameter to also be labelled by using the # prefix in the method signature and I only need to do this for the first parameter.

NOTE: There is no error handling/defensive programming techniques here, if you try and get the left 30 characters out of an alphabet containing 26 characters we'll end up with a crash.  I'll cover error handling in a future blog post.

Pat Delaney

  • No comments found

Leave your comments

terms and condition.

We use cookies to improve our website and your experience when using it. Cookies used for the essential operation of this site have already been set. To find out more about the cookies we use and how to delete them, see our privacy policy.

  I accept cookies from this site.
EU Cookie Directive Module Information