Swift 在字典中搜索
我有一本简单的字典:Swift 在字典中搜索,swift,xcode,Swift,Xcode,我有一本简单的字典: struct AnnotationDict: Encodable, Decodable { let id: Int let index: Int } var sortedAnnotation: [AnnotationDict] = [] let ADict = AnnotationDict(id: 1, index: 2) sortedAnnotation.append(ADict) 如何通过id=1从AnnotationDict搜
struct AnnotationDict: Encodable, Decodable {
let id: Int
let index: Int
}
var sortedAnnotation: [AnnotationDict] = []
let ADict = AnnotationDict(id: 1, index: 2)
sortedAnnotation.append(ADict)
如何通过id=1从AnnotationDict搜索中获取索引?您没有字典。您有一个结构数组 Larme给了你答案:
let itemWithID1 = sortedAnnotation.first(where: { $0.id == 1})
或者更一般地说
func itemWithIndex(_ index: Int, inAnnotationDictArray annotationDictArray: [AnnotationDict]) -> AnnotationDict? {
return annotationDictArray.first(where: { $0.id == index})
}
请注意,
first(其中:)
在O(n)
时间中运行,因此速度会很慢,而在O(n^2)
时间中运行的表达式很容易创建,但却没有意识到这一点。(对于那些没有正式CS背景的人来说,这意味着“完成的时间随着元素数量的平方而增加,因此很容易编写比非常少量的项目更慢的代码。”)在真正的字典中查找项目需要花费大量时间≈恒定时间,这更好。就像其他人说的,你没有字典,你有数组
let item=sortedAnnotation.first{$0.id==1}
返回id==1的第一个项。请注意,返回项目的类型是可选的,即AnnotationDict?
要获取其索引,请执行item!。索引
,但不建议强制展开。首先(其中:{$0.id==1})
,但要澄清。您有一个Struct
数组,它不是真正的“在字典中搜索”。