删除字典指定索引处的值 swift

Removing a value at a specified index of a dictionary swift

我正在编写一个从应用程序 NSUserDefaults 中删除搜索的函数。该方法从搜索字典中删除已删除的搜索。我对这个函数的语法感到困惑。我不明白我们如何使用 searches[tags[index]] 访问 searches Dictionary 的值。要访问 searches Dictionary 索引处的值,我们不会只说 searches[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]]
        }

由于您的字典属于 type [String:String] 以访问或向其添加值,因此键的类型应为 String 而不是 Intindex 属于类型 Int。所以如果我们做 return searches[index] 就会报错。由于 tagsString 类型,我们可以将其用作 searches.

的键

以下是一些对您有帮助的链接:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.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]]
}