我正在编写一个从应用程序NSUserDefaults删除搜索的功能。该方法从搜索词典中删除已删除的搜索。我对这个函数的语法感到困惑。我不明白我们如何使用搜索[tags [index]]访问搜索词典的值。要访问搜索字典索引处的值,我们不会只是说搜索[index]?
private var searches: Dictionary <String, String> = [:] // stores tag-query pairs
private var tags: Array<String> = [] // stores tags in user-specified order
// returns the query String for the taga at a given index
func queryForTagAtIndex(index: Int) -> String? {
return searches[tags[index]]
}
答案 0 :(得分:1)
由于您的词典属type [String:String]
来访问或添加值,因此密钥应为String
类型,而不是Int
。 index
属于Int
类型。因此,如果我们执行return searches[index]
,则会出错。由于tags
的类型为String
,因此我们可以将其用作searches
的关键字。
以下是一些可以帮助您的链接:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
为了便于阅读,我会编辑代码:
private var searches:[String:String]=[String:String]() // stores tag-query pairs
private var tags:[String] = [String]() // stores tags in user-specified order
// returns the query String for the taga at a given index
func queryForTagAtIndex(index: Int) -> String? {
return searches[tags[index]]
}