arraysswiftswift-extensions

How to determine concrete type in extension?


I want to extend Array to translate arrays into sets, where possible. The following extension does that but in the debugger console, the elements of the set are explicitly labeled AnyHashable. Why is this so? But more importantly, is there a way to determine the concrete type of the element (i.e. String) in the extension so that it returns a type-matching set?

extension Array where Element: Hashable {
    var asSet: Set<AnyHashable> {
        return Set(self)
    }
}

let someArray: [String] = ["kiwi", "mango", "mango"]

print(someArray.asSet) // actual output:  [AnyHashable("kiwi"), AnyHashable("mango")]
                       // desired output: ["kiwi", "mango"]

Solution

  • You can just avoid AnyHashable, and return a set of the generic type:

    var asSet: Set<Element> {
        return Set(self)
    }
    

    In your example, that will return a Set<String>.