【问题标题】:How to remove a key-value pair from swift dictionary?如何从 swift 字典中删除键值对?
【发布时间】:2015-12-27 02:35:10
【问题描述】:

我想像示例中那样从字典中删除一个键值对。

var dict: Dictionary<String,String> = [:]
//Assuming dictionary is added some data.
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need

【问题讨论】:

    标签: swift dictionary swift2


    【解决方案1】:

    你可以用这个:

    dict[willRemoveKey] = nil
    

    或者这个:

    dict.removeValueForKey(willRemoveKey)
    

    唯一的区别是第二个将返回删除的值(如果不存在则返回 nil)

    斯威夫特 3

    dict.removeValue(forKey: willRemoveKey)
    

    【讨论】:

    • 现在应该将其命名为 dict.removeValue(willRemoveKey),因为 .removeValueForKey 似乎已重命名 - 感谢您的帮助!
    • 好漂亮,好干净。喜欢它!
    • 如果你的值是可选的,下标语法如何工作?
    • 有没有其他人注意到文档说这是 O(n),其中 n 是字典的大小?!
    • @WiseOldDuck 将下标分配给nil 始终会删除密钥。要在具有可选值类型的字典中分配真正的 nil 值,请分配 .some(nil)
    【解决方案2】:

    Swift 5Swift 4Swift 3

    x.removeValue(forKey: "MyUndesiredKey")

    干杯

    【讨论】:

      【解决方案3】:
      dict.removeValue(forKey: willRemoveKey)
      

      或者你可以使用下标语法:

      dict[willRemoveKey] = nil
      

      【讨论】:

        【解决方案4】:

        删除并在 LOOP 中检查条件

        var eventDateDict = [String:String]()
        //Declarations
        var tempDict = eventDateDict
        
                for value in tempDict{
                    let getDate = value.key
                    if getDate < Date(){
                        eventDateDict.removeValue(forKey: value.key)
                    }
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-18
          • 2019-05-04
          • 2023-03-18
          • 2021-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-23
          相关资源
          最近更新 更多