Extending Set where it contains a generic type?

I have this generic type:

struct ObjectFailure<T: Object> : Hashable {

    let object: T
    let error: Error
}

And I want to create a convenience method on Set whenever it contains an ObjectFailure<T> but is that actually possible with Swift? I've tried many things but can't get it to work. The extension doesn't know what T is obviously...

extension Set where Element == ObjectFailure<T> {

    func contains(object: Object) -> Bool {
        for element: Element in self {
            if element.object === object {
                return true
            }
        }
        return false
    }
}

The trick is to make contains(object:) generic

extension Set {
    func contains<U>(object: U) -> Bool where Element == ObjectFailure<U> {
        for element: Element in self {
            if element.object == object {
                return true
            }
        }
        return false
    }
}
2 Likes

No, you would need generic extensions for that. Hopefully we'll have them soon-ish, although possibly not in 5.1.

See this discussion for more info: Parameterized Extensions

EDIT: Or, yes, sink the generic constraint down to the individual additions, as @cukr suggests. Although this won't work for computed properties, which cannot be made generic.

2 Likes

Thank you both (@Karl) very very much! Super happy with that. :-)

2 Likes