Sorry the title is a mouthful.
I have a protocol that refines Collection with a new subscript that overloads subscript(position: Index) -> Element:
public protocol Foo: Collection {
subscript(array: [Int]) -> Element { get set }
}
extension Foo where Index == Int {
public subscript(array: [Int]) -> Element {
get { self[array.count] }
set { self[array.count] = newValue }
// ^
// error: cannot convert value of type 'Int' to expected argument type '[Int]'
}
}
It seems that it tried to call subscript(array: [Int]) instead of subscript(position: Index). It also seems to only happen with collection. For example, this following code works:
protocol A {
subscript(index: Int) -> Bool { get set }
}
protocol B: A {
subscript(array: [Int]) -> Bool { get set }
}
extension B {
subscript(array: [Int]) -> Bool {
get { self[array.count] }
set { self[array.count] = newValue }
}
}
Did I do some thing wrong in the first code snippet, or is there any way to work around it?
xwu
(Xiaodi Wu)
2
Yes. Notice that you're getting an error on the setter and not the getter, and notice the difference between the requirement on Collection and the requirement in your protocol A:
`Collection`
subscript(position: Self.Index) -> Self.Element { get }
^^^
`A`
subscript(index: Int) -> Bool { get set }
^^^^^^^
In other words, it's not calling what you think it should be calling because there's no such setter.
2 Likes