通用项的数组扩展 - 协议不可转换为父协议

时间:2017-04-24 20:03:42

标签: arrays generics swift3 extension-methods swift3.1

代码:

protocol AProtocol {}

protocol ABProtocol: AProtocol {}

struct ABStruct: ABProtocol {}

struct Wrapper<T> {
    let object: T
}

extension Array where Element == Wrapper<AProtocol> {
    func merge(with otherArray: [Element]) {}
}

let wrapper1: Wrapper<ABProtocol> = Wrapper(object: ABStruct())
let wrapper2: Wrapper<ABProtocol> = Wrapper(object: ABStruct())
let wrappers1 = [wrapper1, wrapper2]
let wrappers2 = [wrapper2, wrapper1]
// Following produces compilation error:
// '[Wrapper<ABProtocol>]' is not convertible to 'Array<Wrapper<AProtocol>>'
let result = wrappers1.merge(to: wrappers2)

这会产生编译错误:

'[Wrapper<ABProtocol>]' is not convertible to 'Array<Wrapper<AProtocol>>'

即使ABProtocol继承(延伸)AProtocol

是否可以为约束于协议的通用元素和从中继承的任何子协议声明Array(或Collection)扩展?

要点: https://gist.github.com/lukaszmargielewski/48fe181264bbc468e1c3b80aec0a6516

0 个答案:

没有答案