You can do something like this:
extension Collection where Element: Collection, Index == Element.Index {
subscript(i: Index, j: Index) -> Element.Element {
get { return self[i][j] }
}
}
extension MutableCollection where Element: MutableCollection, Index ==
Element.Index {
subscript(i: Index, j: Index) -> Element.Element {
get { return self[i][j] }
set { return self[i][j] = newValue }
}
}
Now you can say:
var a: [[Int]] = [[1,0,0],[0,1,0],[0,0,1]]
print(a[2,2])
a[2,2] = 5
print(a[2,2])
Extending the generic protocols instead of concrete types is usually better.
Look at the protocols that define the API of the Array you are interested in
and extend those underlying protocols.
> On Jul 30, 2017, at 3:19 AM, Trevör ANNE DENISE via swift-users
> <[email protected]> wrote:
>
> I am trying to extend a 2D array, doing something like this:
> extension Array where Element == Array<T: Comparable> {
> }
>
> But this doesn't work ! Is there a way to do this ?
>
> Thank you ! :)
>
> Trevör
> _______________________________________________
> swift-users mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-users
_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users