[英]Array of types responding to protocol in Swift
我正在寻找一种方法来创建响应Swift 3协议的类型数组。
这是我的问题(针对示例进行了简化),我有一个名为Rule
的协议:
protocol Rule {
static func check(_ system: MySystem) -> [Inconsistency]
}
和一些响应规则协议的类型:
struct FirstRule : Rule {
static func check(_ system: MySystem) -> [Inconsistency] {
...
}
}
struct SecondRule : Rule {
static func check(_ system: MySystem) -> [Inconsistency] {
...
}
}
现在我想以这种方式检查我的系统:
let system = MySystem()
let inconsistencies = system.check([FirstRule, SecondRule])
为了做到这一点,我只需要编写一个简单的扩展:
extension MySystem {
func check(_ rules : [????]) -> [Inconsistency] {
var result = [Inconsistency]()
for rule in rules {
result += rule.check(self)
}
return result
}
}
那么rules
数组的类型是什么?
当然,我希望保持规则检查静态,并且不想创建实例(在这种情况下,类型将是[Rule]
并且会容易得多)。
因此,如果有人可以提供帮助,将不胜感激。 提前致谢。
该死! 我刚刚找到了! 这是Rule.Type
:
但我必须将.self
添加到类型中:
let inconsistencies = system.check([FirstRule.self, SecondRule.self])
func check(_ rules : [Rule.Type]) -> [Inconsistency]
不管怎么说,还是要谢谢你!
如果您简化除基本要素之外的所有内容,则更容易弄清楚这一点:
protocol Rule {
static func check()
}
struct S1 : Rule {
static func check() {}
}
struct S2 : Rule {
static func check() {}
}
现在:
let arr : [Rule.Type] = [S1.self, S2.self]
for thing in arr {
thing.check()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.