Swift 快速警告-从';[(键:字符串,值:Int)]';不相关类型';[字符串:Int]';总是失败
根据字典:Swift 快速警告-从';[(键:字符串,值:Int)]';不相关类型';[字符串:Int]';总是失败,swift,Swift,根据字典: let dictionary = [ "one": 1, "two": 2, "three": 3] 我想创建一个新版本,根据其密钥删除其中一项。所以我试着用 let dictionaryWithTwoRemoved = dictionary.filter { $0.0 != "two" } 。。。这达到了我想要的,但是这两本字典有不同的类型 `dictionary` is a `[String: Int]` `dictionaryWithTwoRemoved` is a `[(
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]
…我得到以下警告
从“[(键:字符串,值:Int)]”强制转换为不相关的类型“[字符串:
Int]'总是失败
代码在运行时也会因EXC_BAD_指令而崩溃
救命啊 您可以使用
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
}
您可以使用
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
}
如果您想要一个扩展方法来帮助您删除这里的值,您可以
extension Dictionary {
func removingValue(forKey key: Key) -> [Key: Value] {
var mutableDictionary = self
mutableDictionary.removeValue(forKey: key)
return mutableDictionary
}
}
如果您想要一个扩展方法来帮助您删除这里的值,您可以
extension Dictionary {
func removingValue(forKey key: Key) -> [Key: Value] {
var mutableDictionary = self
mutableDictionary.removeValue(forKey: key)
return mutableDictionary
}
}
字典
还没有过滤器
功能。您正在使用序列中的过滤器
,但是字典
是一个键值对序列。调用filter
后,它不再是字典,而是键值对列表。比较。dictionary
还没有filter
功能。您正在使用序列中的过滤器
,但是字典
是一个键值对序列。调用filter
后,它不再是字典,而是键值对列表。比较。