答案 0 :(得分:1)
我可能会稍微误解你的目标,但你应该能够使用反射。这样的事情怎么样?
protocol One {}
protocol Two {}
protocol Three {}
var protocols: [Any] = [One.self, Two.self]
func findProtocol(aProtocol: Any) -> Bool {
let findMirror = Mirror(reflecting: aProtocol)
for checkProtocol in protocols {
let mirror = Mirror(reflecting: checkProtocol)
if findMirror.subjectType == mirror.subjectType {
return true
}
}
return false
}
findProtocol(One) // Returns true
findProtocol(Two) // Returns true
findProtocol(Three) // Returns false
答案 1 :(得分:1)
如果您知道自己比较类型,则应使用更合适的类型(Any.Type
):
var protocolArray: [Any.Type] = [...]
func findProtocol(aProtocol: Any.Type) -> Bool {
// you can do that because Any.Type has an == operator
return protocolArray.contains{ $0 == aProtocol }
}
对于Any
类型,您必须投射它:
var protocolArray: [Any] = [...]
func findProtocol(aProtocol: Any) -> Bool {
return protocolArray.contains{
if let p1 = $0 as? Any.Type, p2 = aProtocol as? Any.Type {
return p1 == p2
}
return false
}
}