【问题标题】:Removing a value at a specified index of a dictionary swift快速删除字典指定索引处的值
【发布时间】:2015-02-20 06:32:52
【问题描述】:

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

【问题讨论】:

    标签: ios xcode swift dictionary


    【解决方案1】:

    由于您的字典属于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]]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2012-11-30
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多