Swift Language Using protocols as first class types


Protocol oriented programing can be used as a core Swift design pattern.

Different types are able to conform to the same protocol, value types can even conform to multiple protocols and even provide default method implementation.

Initially protocols are defined that can represent commonly used properties and/or methods with either specific or generic types.

protocol ItemData {
    var title: String { get }
    var description: String { get }
    var thumbnailURL: NSURL { get }
    var created: NSDate { get }
    var updated: NSDate { get }

protocol DisplayItem {
    func hasBeenUpdated() -> Bool
    func getFormattedTitle() -> String
    func getFormattedDescription() -> String


protocol GetAPIItemDataOperation {
    static func get(url: NSURL, completed: ([ItemData]) -> Void)

A default implementation for the get method can be created, though if desired conforming types may override the implementation.

extension GetAPIItemDataOperation {
    static func get(url: NSURL, completed: ([ItemData]) -> Void) {
        let date = NSDate(
        timeIntervalSinceNow: NSDate().timeIntervalSince1970
            + 5000)
        // get data from url
        let urlData: [String: AnyObject] = [
            "title": "Red Camaro",
            "desc": "A fast red car.",
            "created": NSDate(), "updated": date]
        // in this example forced unwrapping is used
        // forced unwrapping should never be used in practice
        // instead conditional unwrapping should be used (guard or if/let)
        let item = Item(
            title: urlData["title"] as! String,
            description: urlData["desc"] as! String,
            thumbnailURL: NSURL(string: urlData["thumb"] as! String)!,
            created: urlData["created"] as! NSDate,
            updated: urlData["updated"] as! NSDate)

struct ItemOperation: GetAPIItemDataOperation { }

A value type that conforms to the ItemData protocol, this value type is also able to conform to other protocols.

struct Item: ItemData {
    let title: String
    let description: String
    let thumbnailURL: NSURL
    let created: NSDate
    let updated: NSDate

Here the item struct is extended to conform to a display item.

extension Item: DisplayItem {
    func hasBeenUpdated() -> Bool {
        return updated.timeIntervalSince1970 >
    func getFormattedTitle() -> String {
        return title.stringByTrimmingCharactersInSet(
    func getFormattedDescription() -> String {
        return description.stringByTrimmingCharactersInSet(

An example call site for using the static get method.

ItemOperation.get(NSURL()) { (itemData) in
    // perhaps inform a view of new data
    // or parse the data for user requested info, etc.
    dispatch_async(dispatch_get_main_queue(), { 
        // self.items = itemData

Different use cases will require different implementations. The main idea here is to show conformance from varying types where the protocol is the main point of the focus in the design. In this example perhaps the API data is conditionally saved to a Core Data entity.

// the default core data created classes + extension
class LocalItem: NSManagedObject { }

extension LocalItem {
    @NSManaged var title: String
    @NSManaged var itemDescription: String
    @NSManaged var thumbnailURLStr: String
    @NSManaged var createdAt: NSDate
    @NSManaged var updatedAt: NSDate

Here the Core Data backed class can also conform to the DisplayItem protocol.

extension LocalItem: DisplayItem {
    func hasBeenUpdated() -> Bool {
        return updatedAt.timeIntervalSince1970 >
    func getFormattedTitle() -> String {
        return title.stringByTrimmingCharactersInSet(
    func getFormattedDescription() -> String {
        return itemDescription.stringByTrimmingCharactersInSet(

// In use, the core data results can be
// conditionally casts as a protocol
class MyController: UIViewController {

    override func viewDidLoad() {
        let fr: NSFetchRequest = NSFetchRequest(
        entityName: "Items")
        let context = NSManagedObjectContext(
        concurrencyType: .MainQueueConcurrencyType)
        do {
            let items: AnyObject = try context.executeFetchRequest(fr)
            if let displayItems = items as? [DisplayItem] {
        } catch let error as NSError {