How can I make dedicated generic constrained getter?

I can make instance method for dedicated generic constrained method like below

// this is just an example
extension Array  {
    
    func getArrayFirst<T>() -> T? where Element == Array<T> {
        first?.first
    }
}

but how can I define getter like this?

// Error: Same-type constraint 'Element' == 'Array<Element.Element>' is recursive
extension Array where Element == Array<Element.Element> {
    var arrayFirst: Element.Element? {
        return first?.first
    }
}

// Cannot build rewrite system for generic signature; concrete nesting limit exceeded
//Failed rewrite rule is τ_0_0.[concrete: Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<Array<τ_0_0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] => τ_0_0
extension Array where Element == Array {
    var arrayFirst: Element.Element? {
        return first?.first
    }
}

extension Array  {
// Error: Cannot find type 'T' in scope
    var myFirst: T? where Element == Array<T> {
        first?.first
    }
}

extension Array  {
//Error: 'Element' is not a member type of type 'Element'
    var myFirst: Element.Element? where Element == Array<T> {
        first?.first
    }
}

Any help is appreciated.

1 Like

If you can relax your constraint from Array to Collection:

extension Array where Element: Collection {
  var arrayFirst: Element.Element? {
    return first?.first
  }
}

If you can't do that for some reason just add your own dedicated protocol, conform Array to it and do the same thing

protocol _ArrayProtocol {
  associatedtype Element
  var first: Element? { get }
}

extension Array: _ArrayProtocol {}

extension Array where Element: _ArrayProtocol {
  var arrayFirst: Element.Element? {
    return first?.first
  }
}
2 Likes

This is not supported, but maybe one day. It's called "parameterized extensions": swift/docs/GenericsManifesto.md at main · swiftlang/swift · GitHub

It was also previously pitched here: Parameterized Extensions

3 Likes

I forgot about this kind of work around. Thanks for reminding me.

Thanks for clarifying the keyword. It's surprising that the the pitch was never reviewed.