Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 快速警告-从';[(键:字符串,值:Int)]';不相关类型';[字符串:Int]';总是失败_Swift - Fatal编程技术网

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
后,它不再是字典,而是键值对列表。比较。