"If you put both extensions in your code, the faster Hashable version will be used when possible, and the Equatable version will be used as a fallback " —> Is it a compiler knowing what to use and when kind of thing?
public extension Sequence where Element: Hashable {
var firstUniqueElements: [Element] {
var set: Set<Element> = []
return filter { set.insert($0).inserted }
}
}
public extension Sequence where Element: Equatable {
var firstUniqueElements: [Element] {
reduce(into: []) { uniqueElements, element in
if !uniqueElements.contains(element) {
uniqueElements.append(element)
}
}
}
}
Also any reason for why I am able to use this on a [Element] in the console but not in a file?
Yes. It’s the same concept as why you can put default implementations in protocol extensions, and have the compiler use specific implementations for concrete types. Hashable implements Equatable, so it’s essentially an “override”.
Weird case of me being able to invoke the method on [Element] via po [Element].firstUniqueElements in the console but can’t seem to invoke it in a .swift file on [Element]