我对Array的扩展有问题,我试图添加一个方法来检测是否有任何重复,如果我使它成为一个全局函数它可以工作,但是,当我尝试使它成为一个抱怨的Array扩展中的方法:
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")
}
我做错了什么?或者它是XCode中的错误?
答案 0 :(得分:3)
如果没有指定通用参数,则不能将Array
用作类型:
替换:
Array.hasDuplicates(arrayWithDuplicates)
与
Array<String>.hasDuplicates(arrayWithDuplicates)