ios - 在swift 2中从对象和键数组创建字典

标签 ios objective-c swift swift2

我有键数组和对象数组,我想创建一个字典,键数组中索引 Y 处的每个键都引用对象数组中相同索引 Y 处的对象,即我想编写这样的代码,但在 Swift 2 中:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:ObjectsArray forKeys:KeysArray];

最佳答案

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]

或更实用和通用的方法

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

关于ios - 在swift 2中从对象和键数组创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35694542/

相关文章:

ios - 在 Scenekit 中添加半透明图像作为纹理

ios - 使用 Devise 通过 iOS 应用程序进行注册、登录和注销

ios - 更新的 iOS 二进制文件未更新 MainView NIB

iphone - UIImage 和 "back"按钮都出现在我的 viewController 中

ios - Presenting ViewController会被加载但不会出现

swift - 为什么 Swift 认为我的数组是一个函数?

android - 抖动错误: Null check operator used on a null value

ios - 旋转 “MoveableImageView” 对象不会原地旋转

ios - 在搜索栏中搜索数组

objective-c - iOS UIInterfaceOrientation 不适用于 iOS 5