在运行时检查协议继承
Check Protocol Inheritance at Runtime
在运行时检查类型的协议一致性很容易:
guard type is Encodable.Type else { ... }
但如果 type
不是 struct
或 class
,而是继承自 Encodable
的 protocol
,则此技术失败。有没有办法对协议进行类似的检查?
这有点老套,但它可能会解决您的问题:
鉴于这些示例类型:
protocol Animal: Encodable {}
struct Person: Animal {}
protocol SomeOtherProtocol {}
struct Demon: SomeOtherProtocol {}
我通过假设简化了示例的初始化逻辑:
typealias Group = Array
let animals: Group<Animal> = [Person(), Person(), Person()]
let notAnimals: Group<SomeOtherProtocol> = [Demon(), Demon(), Demon()]
这应该适用于自定义集合 class 但是...继续,为您的自定义集合定义以下扩展
extension Group {
func asEncodables() -> Group<Encodable>?{
return self as? Group<Encodable>
}
var isElementEncodable: Bool {
return self is Group<Encodable>
}
}
您现在可以访问以下内容:
animals.asEncodables() //returns some
notAnimals.asEncodables() // returns none
animals.isElementEncodable //true
notAnimals.isElementEncodable //false
所以对于你原来的问题,你可以这样检查:
guard notAnimals.isElementEncodable else { return }
希望对您有所帮助。目前我知道没有办法与类似于 if X is Y
的东西进行比较:/
在运行时检查类型的协议一致性很容易:
guard type is Encodable.Type else { ... }
但如果 type
不是 struct
或 class
,而是继承自 Encodable
的 protocol
,则此技术失败。有没有办法对协议进行类似的检查?
这有点老套,但它可能会解决您的问题:
鉴于这些示例类型:
protocol Animal: Encodable {}
struct Person: Animal {}
protocol SomeOtherProtocol {}
struct Demon: SomeOtherProtocol {}
我通过假设简化了示例的初始化逻辑:
typealias Group = Array
let animals: Group<Animal> = [Person(), Person(), Person()]
let notAnimals: Group<SomeOtherProtocol> = [Demon(), Demon(), Demon()]
这应该适用于自定义集合 class 但是...继续,为您的自定义集合定义以下扩展
extension Group {
func asEncodables() -> Group<Encodable>?{
return self as? Group<Encodable>
}
var isElementEncodable: Bool {
return self is Group<Encodable>
}
}
您现在可以访问以下内容:
animals.asEncodables() //returns some
notAnimals.asEncodables() // returns none
animals.isElementEncodable //true
notAnimals.isElementEncodable //false
所以对于你原来的问题,你可以这样检查:
guard notAnimals.isElementEncodable else { return }
希望对您有所帮助。目前我知道没有办法与类似于 if X is Y
的东西进行比较:/