AProtocol
具有关联类型
AType
还有一个函数
aFunc
. 我想延长
Array
通过使用其元素的结果使其符合协议
aFunc公司
Aprotocol
并且具有相同的关联类型,所以我设置了这个玩具示例:
protocol AProtocol {
associatedtype AType
func aFunc(parameter:AType) -> Bool
}
extension Array : AProtocol where Element : AProtocol, Element.AType == Int {
func aFunc(parameter: Int) -> Bool {
return self.reduce(true, { r,e in r || e.aFunc(parameter: parameter) })
}
}
extension String : AProtocol {
func aFunc(parameter: Int) -> Bool {
return true
}
}
extension Int : AProtocol {
func aFunc(parameter: Int) -> Bool {
return false
}
}
对于仅包含一种类型的数组,此操作很有效:
let array1 = [1,2,4]
array1.aFunc(parameter: 3)
但是对于异构阵列,我得到了错误
Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional
然后
Value of type '[Any]' has no member 'aFunc'
如果注释如下:
let array2 = [1,2,"Hi"] as [Any]
array2.aFunc(parameter: 3)
是否可以按照我的意愿扩展数组,以便允许异类数组,只要它们符合
阿普洛托科尔
有同样的东西
A型