Wednesday, August 13, 2014

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!

No comments:

Post a Comment

I value comments as a way to contribute to the topic and I welcome others' opinions. Please keep comments civil and clean.