UPDATE: The below approach does not work in Swift 2. See the newer post Substrings take 2.

I guessed I’d find a nifty article on just about any Swift topic I needed, which could be linked here. I was wrong. I came to the below conclusion because I couldn’t find any articles (easily) which answered the problem and so had to go digging deeper for myself.

The task was simple. In many languages I’ve used, the simple task of left padding a string to a fixed length has been as simple as

myPaddedString = right("000" + myString, 4)

Usually used with numbers that have been converted to strings, this neatly adds the maximum possible number of leading pad characters, and uses the substring function ‘right’ to ensure only the correct number of digits are returned.

For the life of me I could not find as simple an example of doing the same thing in Swift, nor anything like it. I eventually discovered that the Unicode-ness of Swift strings demands a rather verbose approach to counting off characters, where the above becomes

myPaddedString = myString.substringFromIndex(advance(myString.startIndex, count(myString) - 4))

Not only is it verbose, it names my source variable an astonishing three times!

But, I surmised, at the end of it all, the only input I have provided is the same two values I had in my simple assumptive statement at the top. And this is where some of Swift’s niftier features comes to the rescue – extensions.

It is quite trivial to take the above code and extend the String class.

extension String {
    func right(length : Int) -> String {
        return self.substringFromIndex(advance(self.startIndex, count(self) - length))

After which, the required statement is remarkably close to what I had expected.

myPaddedString = myString.right(2)

I get that there is complexity in Strings, but if I could write a simple extension, I wonder why Apple didn’t.