Protocol extensions and typed arrays

Swift 2.0 introduces protocol extensions, aswel as typed array extensions. This makes it possible to extend an array containing a specific type or even add methods to class inheriting a specific protocol.

Typed array protocol extensions

With typed array extensions you can create methods for Arrays containing a specific type only. For example, if you have a Person struct which inherits the TextRepresentable protocol:

struct Person {
    var name: String
    var age: Int
}

protocol TextRepresentable {
    func asText() -> String
}

// Person inherits TextRepresentable protocol
extension Person: TextRepresentable {
    func asText() -> String {
        return "Person named \(name) aged \(age)"
    }
}

You can create an extension to Array’s containing objects which inherit from TextRepresentable:

extension CollectionType where Generator.Element : TextRepresentable {
    func commaSeperatedString() -> String {
        return ", ".join(map({$0.asText()}))
    }
}

Which allows you to call it like this:

let personOne = Person(name: "Jan", age: 30)
let personTwo = Person(name: "Ellis", age: 28)
let persons:[Person] = [personOne, personTwo]

let string = persons.commaSeperatedString()
print(string)
// Prints out "Person named Jan aged 30, Person named Ellis aged 28"
 

Antoine van der Lee

Dutch iOS developer at Triple. Developed apps like Buienradar, Videoland and Pop the Dots.

 
Follow on Feedly