Vincent Bernier
Vincent Bernier

Reputation: 8664

Swift Protocol as Generic Parameter

Given this class:

class ServiceRegistry {

  var store = [String : AnyObject]()
  var allRegisteredType: [String] {
      return store.map { $0.0 }
  }

  func registerInstance<T>(instance:AnyObject, forType type: T.Type) {
    store[String(type)] = instance
  }

  func instanceForType<T>(type: T.Type) -> T? {
    return store[String(type)] as? T
  }
}

Is there a way I can enforce that T must be a Protocol, without using the @obj?

Upvotes: 3

Views: 1278

Answers (1)

Sentry.co
Sentry.co

Reputation: 5619

This is a modified version of my type assertion technique. I added the "as? AnyClass" assert so that the type can only be of protocol type. There might be a more elegant way of doing this but going through my notes and research about class assertion this is what I came up with.

import Foundation

protocol IDescribable:class{}
class A:IDescribable{}
class B:A{}

let a = A()
let b = B()

func ofType<T>(instance:Any?,_ type:T.Type) -> T?{/*<--we use the ? char so that it can also return a nil*/
    if(instance as? T != nil && type as? AnyClass == nil){return instance as? T}
    return nil
}

Swift.print(ofType(a,A.self))//nil
Swift.print(ofType(a,IDescribable.self))//A
Swift.print(ofType(b,B.self))//nil

Upvotes: 2

Related Questions