aahrens
aahrens

Reputation: 5590

Use Array's Type in Extension Method

What I'm trying to do is create an extension for an Array to check if all the elements are unique. My plan was to create a Set and check the Set's count to the Array's count. However, I'm not sure how to bind the Set's type to the same Type as the Array.

extension Array {
    func unique() -> Bool {
        var set = Set<self>()
        // Now add all the elements to the set
        return set.count == self.count
    }
} 

Upvotes: 2

Views: 71

Answers (1)

Martin R
Martin R

Reputation: 539705

The Array type is defined as

public struct Array<Element>

so Element is the generic placeholder and you can create a Set with the same element type as

let set = Set<Element>()

But you have to require that the array elements are Hashable:

extension Array where Element : Hashable { ... }

(The possibility to define extension methods for generic types with restrictions on the type placeholder was added in Swift 2.)

Finally, with set = Set(self) the set's type is inferred automatically:

extension Array where Element : Hashable {
    func unique() -> Bool {
        let set = Set(self)
        return set.count == self.count
    }
} 

Upvotes: 3

Related Questions