Swift 协议元类型的运行时比较
Runtime comparison of Swift Protocol MetaTypes
我正在尝试将 Swift 协议动态匹配到一个实现,但我在尝试在运行时执行协议比较时遇到了阻碍 - 似乎协议可能并不真正存在于运行时间?
我尝试过的一些例子:
var protocols[Any]
func findProtocol(aProtocol: Any) -> Bool {
// Nope, protocols don't implement equatable
aProtocol == protocols[0]
// Doesn't work, unsafeAddressOf() only applies to AnyObjects
let pointer: UnsafePointer = unsafeAddressOf(aProtocol)
}
我想我可能已经触及了试图打败类型系统的界限……有什么想法吗?
我可能有点误解你想要做什么,但你应该能够为此使用反射。像这样的怎么样?
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
如果您知道比较类型本身,您应该使用更合适的类型 (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{ [=10=] == aProtocol }
}
对于 Any
类型,您必须强制转换它:
var protocolArray: [Any] = [...]
func findProtocol(aProtocol: Any) -> Bool {
return protocolArray.contains{
if let p1 = [=11=] as? Any.Type, p2 = aProtocol as? Any.Type {
return p1 == p2
}
return false
}
}
我正在尝试将 Swift 协议动态匹配到一个实现,但我在尝试在运行时执行协议比较时遇到了阻碍 - 似乎协议可能并不真正存在于运行时间?
我尝试过的一些例子:
var protocols[Any]
func findProtocol(aProtocol: Any) -> Bool {
// Nope, protocols don't implement equatable
aProtocol == protocols[0]
// Doesn't work, unsafeAddressOf() only applies to AnyObjects
let pointer: UnsafePointer = unsafeAddressOf(aProtocol)
}
我想我可能已经触及了试图打败类型系统的界限……有什么想法吗?
我可能有点误解你想要做什么,但你应该能够为此使用反射。像这样的怎么样?
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
如果您知道比较类型本身,您应该使用更合适的类型 (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{ [=10=] == aProtocol }
}
对于 Any
类型,您必须强制转换它:
var protocolArray: [Any] = [...]
func findProtocol(aProtocol: Any) -> Bool {
return protocolArray.contains{
if let p1 = [=11=] as? Any.Type, p2 = aProtocol as? Any.Type {
return p1 == p2
}
return false
}
}