[英]Heterogeneous array that conforms to protocol with associated type in Swift
我有一个协议AProtocol
与关联类型AType
和 function aFunc
。 我想扩展Array
使其符合协议,方法是使用其元素aFunc
function 的结果。 显然,这只有在数组的元素符合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
}
}
这适用于仅包含一种类型的 arrays :
let array1 = [1,2,4]
array1.aFunc(parameter: 3)
但是对于异构 arrays,我收到错误Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional
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)
是否可以按照我的意愿扩展 Array 以便允许异构 arrays 只要它们符合AProtocol
并且具有相同的AType
?
看看这是否符合您的需求。
删除关联类型
protocol BProtocol {
func aFunc(parameter: BProtocol) -> Bool
}
extension String : BProtocol {
func aFunc(parameter: BProtocol) -> Bool {
return true
}
}
extension Int : BProtocol {
func aFunc(parameter: BProtocol) -> Bool {
return false
}
}
extension Array : BProtocol where Element == BProtocol {
func aFunc(parameter: BProtocol) -> Bool {
return self.reduce(true, { r,e in r || e.aFunc(parameter: parameter) })
}
}
let a1 : [BProtocol] = [1, 2, 3, "Hi"]
let boolean = a1.aFunc(parameter: 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.