gpt4 book ai didi

swift - Swift 中协议(protocol)的类型约束问题

转载 作者:可可西里 更新时间:2023-11-01 01:43:34 24 4
gpt4 key购买 nike

我有一个协议(protocol)AProtocol,它有一些数据结构和一个协议(protocol)BProtocol,它有一个采取参数符合AProtocol的操作。代码是这样的:

protocol AProtocol {
// data
}

protocol BProtocol {
func action<T: AProtocol>(completionHandle: (Bool, [T]?) -> ())
}

当我实现这些协议(protocol)时 - 一个结构符合 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
}
})
}
}

我想知道为什么我错了,如何解决这个问题。谢谢!

最佳答案

你可以解决它

completionHandle(true, self.structs.map { $0 as T })

我不确定这是一个错误还是语言中的某些限制,禁止您直接转换此数组。这可能是不可能的,因为数组是值类型。

对于您更新的问题:您已为操作方法指定泛型类型,因此编译器无法从上下文中获取类型。您必须明确设置它:

var bClass = BClass()
bClass.action { (boolValue, arrayOfAProtocol: [AProtocol]?) in
if boolValue {
// Do something
}
}

关于swift - Swift 中协议(protocol)的类型约束问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com