1

I have a problem with an extension on Array, I'm trying to add a method to detect if there are any duplicates, if I make it a global function it works, however, when I try to make it a method in an Array extension it complains:

extension Array {
    static func hasDuplicates<T:Hashable>(array:Array<T>) -> Bool {
        var map = Dictionary<T,Bool>()

        for var x = 0; x < array.count; x++ {
            let currentItem = array[x] as T
            if map[currentItem] {
                return true
            } else {
                map[currentItem] = true
            }
        }
        return false
    }
}

func hasDuplicates<T:Hashable>(array:Array<T>) -> Bool {
    var map = Dictionary<T,Bool>()

    for var x = 0; x < array.count; x++ {
        let currentItem = array[x] as T
        if map[currentItem] {
            return true
        } else {
            map[currentItem] = true
        }
    }
    return false
}

func testDuplicates() {
    var arrayWithDuplicates = [ "not repeated", "is repeated", "not repeated again", "repeated", "this isn't repeated", "repeated", "is repeated" ]
    var arrayWithoutDuplicates = [ "not repeated", "not repeated again","this isn't repeated", "isn't repeated" ]

    XCTAssert(hasDuplicates(arrayWithDuplicates), "There ARE duplicates")
    XCTAssert(hasDuplicates(arrayWithoutDuplicates) == false, "There AREN'T any duplicates")

    // Shows an error: Cannot convert the expression's type 'Void' to type 'String'        
    XCTAssert(Array.hasDuplicates(arrayWithDuplicates), "There ARE duplicates")
    XCTAssert(Array.hasDuplicates(arrayWithoutDuplicates) == false, "There AREN'T any duplicates")
}

What am I doing wrong? or is it a bug in XCode?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Emanuel
  • 1,981
  • 1
  • 20
  • 28
  • possible duplicate of [How can I extend typed Arrays in Swift?](http://stackoverflow.com/questions/24027116/how-can-i-extend-typed-arrays-in-swift) – ColinE Jun 11 '14 at 20:20

1 Answers1

3

You cannot use Array as a type without specifying the generic parameter:

Replace:

Array.hasDuplicates(arrayWithDuplicates)

with

Array<String>.hasDuplicates(arrayWithDuplicates)
Sulthan
  • 128,090
  • 22
  • 218
  • 270