Dictionary 如果我只想确定存在一个值,我应该使用哪个Swift数据结构?
我在看一堆名字,我想记录下所有的名字。我的计划是迭代名称数组,并使用字典跟踪每个名称,这样我就可以在O(1)时间内在字典中查找名称,看看它是否存在 Swift中的最佳数据结构是什么?(我很想知道最适合这种情况的通用数据结构的名称,即使它不在Swift中。) 一个Dictionary 如果我只想确定存在一个值,我应该使用哪个Swift数据结构?,dictionary,data-structures,language-agnostic,swift,Dictionary,Data Structures,Language Agnostic,Swift,我在看一堆名字,我想记录下所有的名字。我的计划是迭代名称数组,并使用字典跟踪每个名称,这样我就可以在O(1)时间内在字典中查找名称,看看它是否存在 Swift中的最佳数据结构是什么?(我很想知道最适合这种情况的通用数据结构的名称,即使它不在Swift中。) 一个Dictionary对象就可以了,但它需要一个键值,而我实际上只需要键。您正在寻找一个集合(一个无序的唯一对象的集合-尽管有些实现是有序的) 斯威夫特和客观,这对你不管用吗 Swift不提供集合类型。有关如何定义集合,可以参考 此处复制代
Dictionary
对象就可以了,但它需要一个键值,而我实际上只需要键。您正在寻找一个集合(一个无序的唯一对象的集合-尽管有些实现是有序的)
斯威夫特和客观,这对你不管用吗 Swift不提供集合类型。有关如何定义集合,可以参考 此处复制代码以供快速参考:
struct Set<T: Hashable> {
typealias Element = T
private var contents: [Element: Bool]
init() {
self.contents = [Element: Bool]()
}
/// The number of elements in the Set.
var count: Int { return contents.count }
/// Returns `true` if the Set is empty.
var isEmpty: Bool { return contents.isEmpty }
/// The elements of the Set as an array.
var elements: [Element] { return Array(self.contents.keys) }
/// Returns `true` if the Set contains `element`.
func contains(element: Element) -> Bool {
return contents[element] ?? false
}
/// Add `newElements` to the Set.
mutating func add(newElements: Element...) {
newElements.map { self.contents[$0] = true }
}
/// Remove `element` from the Set.
mutating func remove(element: Element) -> Element? {
return contents.removeValueForKey(element) != nil ? element : nil
}
}
结构集{
typealias元素=T
私有变量内容:[元素:Bool]
init(){
self.contents=[Element:Bool]()
}
///集合中的元素数。
变量计数:Int{return contents.count}
///如果集合为空,则返回'true'。
var isEmpty:Bool{return contents.isEmpty}
///集合中的元素作为数组。
var元素:[Element]{返回数组(self.contents.keys)}
///如果集合包含'element',则返回'true'。
func包含(元素:元素)->Bool{
返回内容[元素]??错误
}
///将“新元素”添加到集合中。
变异函数添加(新元素:元素…){
newElements.map{self.contents[$0]=true}
}
///从集合中删除'element'。
变异func remove(元素:元素)->element{
返回内容。removeValueForKey(元素)!=nil?元素:nil
}
}
否则,您可以使用Dictionary并将名称用作键和值。您指的是HashSet、HashMap或HashTable。我甚至会使用
[Element:()]