简体   繁体   中英

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.

Damn! I've just found it! It's Rule.Type :

But I have to add .self to the types:

let inconsistencies = system.check([FirstRule.self, SecondRule.self])
func check(_ rules : [Rule.Type]) -> [Inconsistency] 

Thanks anyway!

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM