在扩展方法中使用数组的类型
问题描述:
我想要做的是创建一个数组的扩展来检查是否所有的元素都是唯一的。我的计划是创建一个Set并检查Set的数量到Array的数量。但是,我不确定如何将Set的类型绑定到与Array相同的Type。在扩展方法中使用数组的类型
extension Array {
func unique() -> Bool {
var set = Set<self>()
// Now add all the elements to the set
return set.count == self.count
}
}
答
的Array
类型被定义为
public struct Array<Element>
所以Element
是通用占位符,你可以用相同的元素类型创建 一个Set
作为
let set = Set<Element>()
但你必须要求阵列元素是Hashable
:
extension Array where Element : Hashable { ... }
最后(定义为通用类型 与类型占位符限制在夫特2.加入扩展方法的可能性),与set = Set(self)
集合的类型自动推断出:
extension Array where Element : Hashable {
func unique() -> Bool {
let set = Set(self)
return set.count == self.count
}
}
完全正确。我输了比赛... :))))) – matt
whats'hashable'是什么意思? – Dustin
@Dustin:'Hashable'是*协议*,请参阅https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_Hashable_Protocol/index.html。 –