Zaphod Zaphod - 1 month ago 6
Swift Question

Array of types responding to protocol in Swift

I'm looking for a way to create an array of types responding to a protocol in Swift 3.

Here's my problem (simplified for the example), I have a protocol called

Rule
:

protocol Rule {
static func check(_ system: MySystem) -> [Inconsistency]
}


and some types responding to the Rule protocol:

struct FirstRule : Rule {
static func check(_ system: MySystem) -> [Inconsistency] {
...
}
}

struct SecondRule : Rule {
static func check(_ system: MySystem) -> [Inconsistency] {
...
}
}


Now I wish to check my system this way :

let system = MySystem()
let inconsistencies = system.check([FirstRule, SecondRule])


In order to do that I just have to write a simple extension:

extension MySystem {
func check(_ rules : [????]) -> [Inconsistency] {
var result = [Inconsistency]()

for rule in rules {
result += rule.check(self)
}

return result
}
}


So what would be the type of the
rules
array?

Of course I wish to keep the rule checking static, and do not want to create instances (in that case the type would be
[Rule]
and it would be much easier).

So if anyone can help, it would be much appreciated.
Thanks in advance.

Answer

It's easier to figure this out if you simplify away everything but the essentials:

protocol Rule {
    static func check()
}
struct S1 : Rule {
    static func check() {}
}
struct S2 : Rule {
    static func check() {}
}

And now:

let arr : [Rule.Type] = [S1.self, S2.self]
for thing in arr {
    thing.check()
}
Comments