The code below fails to compile, but I'm not sure what to do to get it to compile and run. Paste in a playground to try it out. I expect it to print "configured" twice. My question is not a duplicate of this. I don't have an array of things that all conform to the protocol. I want to test to see if they conform and only call the method if they do.
My goal is to have it call configure on any object in the array that can handle a MyConfiguration object, otherwise do nothing. Any ideas?
protocol Configurable {
associatedtype Configuration
func configure(with configuration: Configuration)
}
struct MyConfiguration { }
class Base { }
class A: Base, Configurable {
func configure(with configuration: MyConfiguration) {
print("configured")
}
}
class B: Base { }
extension Array where Iterator.Element == Base {
func configure(with configuration: MyConfiguration) {
for each in self {
if let configurable = each as? Configurable {
configurable.configure(with: configuration)
}
}
}
}
let array: [Base] = [A(), B(), A()]
let conf = MyConfiguration()
array.configure(with: conf)