With Swift 2, you can write permute() as a method on Dictionary (assume that all keys and values are unique):
extension Dictionary where Value: Hashable {
func permute() -> [Value: Key] {
var permuted = [Value: Key]()
for (key, value) in self {
permuted[value] = key
}
return permuted
}
}
By "permute", I mean specifically that keys become the values and vice versa.
But what if you wanted to write this more generically so that any sequence of (key, value) tuples in which the values were hashable could be converted to a permuted dictionary. Is it possible?
I'm thinking something like:
extension SequenceType where Generator.Element: (Any, Hashable) {
func permute() -> [Generator.Element.1: Generator.Element.0] {
...
}
}
Or perhaps:
extension SequenceType<Key, Value: Hashable> where Generator.Element == (Key, Value) {
func permute() -> [Value: Key] {
...
}
}
But these are both nonstarters. In the first version, it's not clear what "Generator.Element: (Any, Hashable)" would mean, and the compiler doesn't accept it anyway. It also doesn't understand the notation Generator.Element.1, so apparently it's not possible to look inside tuple types in the way that you can with actual tuples.
In the second version, the compiler complains "expected '>' to complete generic argument list", by which I think it means, "hey, you can't treat Sequence as a generic type to be specialized, since it isn't generic to begin with". (It doesn't matter if you move the > to the end.)
Can generics and tuples interact?