Is there an easier way to access a super-class/protocol version of a method

I'm making versions of a method for both Collection and Sequence. All the objects I'm testing on are some form of Collection, which means I use AnySequence(x) any time I want to call the Sequence version for testing. Is there an easier way like "as Sequence" or "x.(Sequence.myAwesomeMethod)(...)" or something else I missed?

I just want to avoid the hit of AnySequence if I don't have to.

One thing I can think of is to make a new function to avoid collision.

extension Sequence {
    func foo() -> String {
        return "Sequence foo"
    }
}

extension Collection {
    func foo() -> String {
        return "Collection foo"
    }
}

extension Sequence {
    func sequenceFoo() -> String {
        return foo()
    }
}

let a = [3, 4, 5]
a.foo() // Collection foo
a.sequenceFoo() // Sequence foo
AnySequence(a).foo() // Sequence foo

This is unfortunately the best answer right now for protocols, and it only works if the method in question is not a protocol requirement. (Same for the AnySequence trick, though.)

For superclasses, that's what super is for.

Added [SR-9792] "Provide some way to call a protocol's base's overload of a method."

Terms of Service

Privacy Policy

Cookie Policy