Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 在字典中搜索_Swift_Xcode - Fatal编程技术网

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
数组,它不是真正的“在字典中搜索”。