I have a protocol AProtocol that has some data structs and a protocol BProtocol that has an action which takes parameters conform to AProtocol. The code goes like this:
protocol AProtocol {
// data
}
protocol BProtocol {
func action<T: AProtocol>(completionHandle: (Bool, [T]?) -> ())
}
When I implement these protocols - A struct conforms to AProtocol and a class conforms to BProtocol, I cannot find a way to satisfy the compiler.
struct AStruct: AProtocol {
}
class BClass: BProtocol {
var structs = [AStruct]()
func action<T : AProtocol>(completionHandle: (Bool, [T]?) -> ()) {
completionHandle(true, self.structs) // Compile error: "'AStruct' is not identical to 'T'"
}
}
Updated:
I tried using type casting, but failed to invoke the action with another error("Cannot convert the expression's type '(($T4, ($T4, $T5) -> ($T4, $T5) -> $T3) -> ($T4, ($T4, $T5) -> $T3) -> $T3, (($T4, $T5) -> ($T4, $T5) -> $T3, $T5) -> (($T4, $T5) -> $T3, $T5) -> $T3) -> (($T4, ($T4, $T5) -> $T3) -> $T3, (($T4, $T5) -> $T3, $T5) -> $T3) -> $T3' to type 'AProtocol'"):
class BClass: BProtocol {
var structs = [AStruct]()
func action<T : AProtocol>(completionHandle: (Bool, [T]?) -> ()) {
completionHandle(true, self.structs.map({$0 as T})) // Now the compile error has gone
}
func testAction() {
self.action({ // Compile error: "Cannot convert the expression's type..."
(boolValue, arrayOfStructs) in
if boolValue {
// Do something
}
})
}
}
I wonder why am I wrong and how to solve the problem. Thank you!