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?