gpt4 book ai didi

arrays - 在扩展方法中使用数组的类型

转载 作者:可可西里 更新时间:2023-11-01 01:03:32 26 4
gpt4 key购买 nike

我想做的是为数组创建一个扩展,以检查所有元素是否都是唯一的。我的计划是创建一个 Set 并检查 Set 的计数与 Array 的计数。但是,我不确定如何将 Set 的类型绑定(bind)到与 Array 相同的类型。

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 { ... }

(为泛型定义扩展方法的可能性在 Swift 2 中添加了对类型占位符的限制。)

最后,使用 set = Set(self) 自动推断集的类型:

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

关于arrays - 在扩展方法中使用数组的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com