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中将字典值转换为其他类型_Swift_Dictionary - Fatal编程技术网

在Swift中将字典值转换为其他类型

在Swift中将字典值转换为其他类型,swift,dictionary,Swift,Dictionary,我有一本字典。我想通过它,并将值转换为不同的类型.map{}将是完美的,除非这是一个字典而不是数组。因此,我在堆栈溢出上找到了一个mapPairs函数,它应该适用于字典。不幸的是,我得到了一个转换错误 extension Dictionary { // Since Dictionary conforms to CollectionType, and its Element typealias is a (key, value) tuple, that means you ought

我有一本字典。我想通过它,并将值转换为不同的类型
.map{}
将是完美的,除非这是一个字典而不是数组。因此,我在堆栈溢出上找到了一个mapPairs函数,它应该适用于字典。不幸的是,我得到了一个转换错误

extension Dictionary {
    //    Since Dictionary conforms to CollectionType, and its Element typealias is a (key, value) tuple, that means you ought to be able to do something like this:
    //
    //    result = dict.map { (key, value) in (key, value.uppercaseString) }
    //
    //    However, that won't actually assign to a Dictionary-typed variable. THE MAP METHOD IS DEFINED TO ALWAYS RETURN AN ARRAY (THE [T]), even for other types like dictionaries. If you write a constructor that'll turn an array of two-tuples into a Dictionary and all will be right with the world:
    //  Now you can do this:
    //    result = Dictionary(dict.map { (key, value) in (key, value.uppercaseString) })
    //
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }

    //    You may even want to write a Dictionary-specific version of map just to avoid explicitly calling the constructor. Here I've also included an implementation of filter:
    //    let testarr = ["foo" : 1, "bar" : 2]
    //    let result = testarr.mapPairs { (key, value) in (key, value * 2) }
    //    result["bar"]
    func mapPairs<OutKey: Hashable, OutValue>(@noescape transform: Element throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
        return Dictionary<OutKey, OutValue>(try map(transform))
    }

}

var dict1 = ["a" : 1, "b": 2, "c": 3]

let convertedDict: [String: String] = dict1.mapPairs { // ERROR: cannot convert value of type '_ -> (String, Int)' to expected argument type '(String, Int) -> (String, String)'
    element -> (String, Int) in
        element[0] = String(element.1)
        return element
}
扩展字典{
//由于Dictionary符合CollectionType,并且它的元素typealias是(key,value)元组,这意味着您应该能够执行以下操作:
//
//result=dict.map{(key,value.uppercaseString)中的(key,value)}
//
//但是,这实际上不会分配给字典类型的变量。MAP方法被定义为始终返回数组(即[t]),即使对于字典等其他类型也是如此。如果您编写一个构造函数,将两个元组的数组转换为字典,那么一切都将正常进行:
//现在您可以执行以下操作:
//结果=字典(dict.map{(key,value.uppercaseString)中的(key,value)})
//
init(uu对:[元素]){
self.init()
对于(k,v)成对{
自我[k]=v
}
}
//您甚至可能希望编写特定于词典的map版本,以避免显式调用构造函数。这里我还提供了一个filter的实现:
//设testarr=[“foo”:1,“bar”:2]
//让result=testarr.mapPairs{(key,value)in(key,value*2)}
//结果[“条”]
func映射对(@noescape transform:Element throws->(OutKey,OutValue))rethrows->[OutKey:OutValue]{
返回字典(尝试映射(转换))
}
}
变量dict1=[“a”:1,“b”:2,“c”:3]
let convertedDict:[String:String]=dict1.mapPairs{//错误:无法将类型为“->(String,Int)”的值转换为预期的参数类型“(String,Int)->(String,String)”
元素->中的(字符串,Int)
元素[0]=字符串(元素1)
返回元素
}

如果您想将
[String:Int]
的dict更改为
[String:String]
,您可以执行与我之前的回答相同的操作:

let dict1 = ["a" : 1, "b": 2, "c": 3]
var dict2 = [String: String]()

dict1.forEach { dict2[$0.0] = String($0.1) }

print("\(dict2.dynamicType): \(dict2)")
输出:

Dictionary<String, String>: ["b": "2", "a": "1", "c": "3"]
字典:[“b”:“2”,“a”:“1”,“c”:“3”]
作为方法块给出的示例,您应该像下面这样使用
映射对:

let convertedDict: [String: String] = dict1.mapPairs { (key, value) in
    (key, String(value))
}
请注意,由于Swift支持隐式推理,因此在Swift 5及更高版本中不需要显式返回
return

let originalDict:[TypeA:TypeB]=/**/
让convertedDict:[TypeA:TypeC]=originalDict.mapValues{/*此处转换*/}
例如:

let integerDict:[String:Int]=[“a”:1,“b”:2]
let doubleDict:[String:Double]=integerDict.mapValues(Double.init)
打印(doubleDict)/[“a”:1.0,“b”:2.0]

我不知道这是否有帮助,但由于Swift 4.2有一个名为
mapValues(:)
()的新操作符,它将把您要查找的结果转换为:

let convertedDict = dict1.mapValues { String($0) }

你的问题是什么?如果问题包含一个简单的问题示例,而不是几个函数和冗长的注释,那会很有帮助。我应该从哪里读到
$0.0
/
$0.1
符号,用于索引到闭包的字典参数的键和值?@duncac:我已经尝试过寻找它了有一段时间,但我什么也找不到。老实说,我对这些文档知之甚少,通常我希望通过阅读像您这样经验丰富的用户和其他SO常客的帖子来了解更多:p。