Tah*_*han 1 objective-c ios swift swift2
我有Keys数组和Objects数组,我想创建一个字典,键数组中索引Y处的每个键引用对象数组中相同索引Y处的对象,即我想在Swift 2中创建这样的代码:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:ObjectsArray forKeys:KeysArray];
Run Code Online (Sandbox Code Playgroud)
let keys = [1,2,3,4]
let values = [10, 20, 30, 40]
assert(keys.count == values.count)
var dict:[Int:Int] = [:]
keys.enumerate().forEach { (i) -> () in
dict[i.element] = values[i.index]
}
print(dict) // [2: 20, 3: 30, 1: 10, 4: 40]
Run Code Online (Sandbox Code Playgroud)
或更多功能和通用方法
func foo<T:Hashable,U>(keys: Array<T>, values: Array<U>)->[T:U]? {
guard keys.count == values.count else { return nil }
var dict:[T:U] = [:]
keys.enumerate().forEach { (i) -> () in
dict[i.element] = values[i.index]
}
return dict
}
let d = foo(["a","b"],values:[1,2]) // ["b": 2, "a": 1]
let dn = foo(["a","b"],values:[1,2,3]) // nil
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5321 次 |
| 最近记录: |