简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM