Swift Warning - 从'[(key:String,value:Int)]'转换为不相关的类型'[String:Int]'总是失败

时间:2017-04-05 19:40:39

标签: swift

鉴于字典:

let dictionary = [ "one": 1, "two": 2, "three": 3]

我想创建一个新版本,其中一个项目是根据其键删除的。所以我正在尝试使用......

let dictionaryWithTwoRemoved = dictionary.filter { $0.0 != "two" }

...实现我想要的东西但是这两本词典有不同的类型...

`dictionary` is a `[String: Int]`
`dictionaryWithTwoRemoved` is a `[(key: String, value: Int)]`

这使我的生活变得困难。

如果我试图像这样投...

let dictionaryWithThreeRemoved = dictionary.filter { $0.0 != "three" } as! [String: Int]

......我收到以下警告......

  

从'[(key:String,value:Int)]'转换为不相关的类型'[String:   Int]'总是失败

并且代码也会在运行时与EXC_BAD_INSTRUCTION崩溃。

帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用reduce执行此操作。

//: Playground - noun: a place where people can play

import Cocoa

let dictionary = [ "one": 1, "two": 2, "three": 3]
let newDictionary = dictionary.reduce([:]) { result, element -> [String: Int] in
    guard element.key != "two" else {
        return result
    }

    var newResult = result
    newResult[element.key] = element.value
    return newResult
}

答案 1 :(得分:1)

如果您想要一种扩展方法来帮助您删除这些值,请转到...

extension Dictionary {
    func removingValue(forKey key: Key) -> [Key: Value] {
        var mutableDictionary = self
        mutableDictionary.removeValue(forKey: key)
        return mutableDictionary
    }
}