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

时间:2015-02-20 06:32:53

标签: ios xcode swift dictionary

我正在编写一个从应用程序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]]
        }

1 个答案:

答案 0 :(得分:1)

由于您的词典属type [String:String]来访问或添加值,因此密钥应为String类型,而不是Intindex属于Int类型。因此,如果我们执行return searches[index],则会出错。由于tags的类型为String,因此我们可以将其用作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]]
}