Define functions for generic Set<T>

Suppose I wanted to add some convenience operators for set union, intersection, and subtraction.


I can do it for Set<Character> or any specific type of element, e.g.


func + (left: Set<Character>, right: Set<Character>) -> Set<Character> {
  return left.union(right)
}


But how could I define that so that it will work generically?


So far everything that I've tried has failed. I'm guessing that the solution will involve extending Set, but my grasp of generics is tenuous at this point, so I'd appreaciate help.


None of this is actually vital to anything I'm doing. These definitions are for convenience, but I decided to take the opportunity to play with defining operators.

Accepted Reply

func + <E: Hashable>(left: Set<E>, right: Set<E>) -> Set<E> {
    return left.union(right)
}

I'm afraid you forgot about Set.Element needs conform to Hashable.

Set Structure Reference

Replies

func + <E: Hashable>(left: Set<E>, right: Set<E>) -> Set<E> {
    return left.union(right)
}

I'm afraid you forgot about Set.Element needs conform to Hashable.

Set Structure Reference

This is a minor quibble, OOPer, but actually you need not enforce the Hashable requirement yourself:


func + <E>(left: Set<E>, right: Set<E>) -> Set<E> {
    return left.union(right)
}


The compiler can never be presented with Set<E> arguments where E isn't Hashable (because such types can't exist), so you needn't worry about the consequences of matching them.

Thank you. I found that in Xcode 7.0 beta 5 seems to work without the Hashable as far as Swift is concenred, but it seems to crash SourceKitService each time I type or paste that in.


(Darn. Just as I was going to construct a radar, I can't reproduce that SourceKitService crash any more.)

Thank you.


It wasn't the Hashable that I was forgetting. It was that I misunderstood the syntax of generics. I had been trying stuff like


func + Set<E: Hashable>(left: Set<E>, right: Set<E>) -> Set<E> { 
     return left.union(right) 
}

which obviously failed.