Playing With Swift: Extensions

I am finally getting around to playing with Swift, Apple’s new language for Mac and iOS development. I have to say, I am excited to have a new language to learn. Swift looks very interesting as it pulls in many great features of other modern languages.

Like Objective-C, and Ruby, and probably others that I don’t know about, Swift allows us to add functionality to any class, including the built-in classes like String and Array.

Here are a couple of examples of extending the Array and the String built-in classes to add a join() method.

First, let’s extend the Array class to add a join(sep:String) method that returns a string containing all of the elements of the Array, delimited by the separate value passed in.

extension Array {
    func join(sep:String) -> String {
        var s = ""
        if let firstItem = self.first {
            s = "\(firstItem)"
            for i in 1..<self.count {
                s = s + sep + "\(self[i])"
            }
        }
        return s
    }
}

Pretty cool, right? But what if our religion thinks it’s better to extend String and pass in the list to be joined (Python style)?

extension String {
    func join<T>(list:Array<T>) -> String {
        var s = ""
        if let firstItem = list.first {
            s = "\(firstItem)"
            for str in list[1..<list.count] {
                s = s + self + "\(str)"
            }
        }
        return s
    }
}

Just as easy. Did you notice the slight variation to use a slice of the array, rather than a for-loop?

While I love a good pedantic discussion about which class is more “proper” to extend, you probably don’t have time for such things, so let’s just extend them both. And to keep it DRY, let’s alter our Array extension to call the String extension via the separator argument. (Yes, I’ve been influenced by Python.)

extension Array {
    func join(sep:String) -> String {
        return sep.join(self)
    }
}

One enhancement I would like to make to these methods is to use a default parameter value for the separator. Unfortunately, as of this writing, defining a default parameter causes a segfault in Xcode. It is beta software, after all!

Here’s a small Playground with these extensions. Have fun!

This entry was posted in Software and tagged , , , , . Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>