Swift协议作为通用参数 [英] Swift Protocol as Generic Parameter
本文介绍了Swift协议作为通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提供此类:
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
}
}
有没有一种方法可以强制T
必须是一个协议,而无需使用@obj?
Is there a way I can enforce that T
must be a Protocol, without using the @obj?
推荐答案
这是我的类型声明技术的修改版本.我添加了"as?AnyClass" 断言,以便该类型只能是协议类型. 执行此操作的方法可能更优雅,但请仔细阅读我的笔记并研究有关类断言的内容.
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
这篇关于Swift协议作为通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文