简体   繁体   English

Swift协议作为通用参数

[英]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? 有没有办法我可以强制执行T必须是一个协议,而不使用@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. 我添加了“as?AnyClass”断言,因此类型只能是协议类型。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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