【发布时间】:2014-10-17 07:47:19
【问题描述】:
我有一个协议AProtocol,它有一些数据结构和一个协议BProtocol,它有一个接受符合AProtocol 的参数的操作。代码如下:
protocol AProtocol {
// data
}
protocol BProtocol {
func action<T: AProtocol>(completionHandle: (Bool, [T]?) -> ())
}
当我实现这些协议时——结构符合AProtocol,类符合BProtocol,我找不到满足编译器的方法。
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'"
}
}
更新:
我尝试使用类型转换,但未能调用 action 并出现另一个错误(“无法转换表达式的类型 '(($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' 输入 '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
}
})
}
}
我想知道为什么我错了以及如何解决问题。谢谢!
【问题讨论】:
标签: swift