[swift-users] Extending 2D arrays of genetic type

Hooman Mehr hooman at mac.com
Sun Jul 30 14:09:27 CDT 2017


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 <swift-users at swift.org> 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
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170730/8d2c42db/attachment.html>


More information about the swift-users mailing list