【问题标题】:create dictionary from objects and keys arrays in swift 2在swift 2中从对象和键数组创建字典
【发布时间】:2016-02-29 08:05:12
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c swift swift2


    【解决方案1】:
    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
    

    【讨论】:

    • 你为什么只复制你已经拥有的~~上面~~下面那个人的东西?
    • 在 Swift3 中,enumerate 被替换为 enumerated。一般来说,Swift 3 使用现在时动词来修改对象,过去时动词返回修改后的副本——与 Python 的 sortedsort 进行比较。
    • 在 Swift 3 中,index 变为 offset。还是谢谢!
    【解决方案2】:

    这是一个通用的解决方案

    func dictionaryFromKeys<K : Hashable, V>(keys:[K], andValues values:[V]) -> Dictionary<K, V>
    {
      assert((keys.count == values.count), "number of elements odd")
      var result = Dictionary<K, V>()
      for i in 0..<keys.count {
        result[keys[i]] = values[i]
      }
      return result
    }
    
    let keys = ["alpha", "beta", "gamma", "delta"]
    let values = [1, 2, 3, 4]
    
    let dict = dictionaryFromKeys(keys, andValues:values)
    print(dict)
    

    【讨论】:

      【解决方案3】:

      试试这个:

          let dict = NSDictionary(objects: <Object_Array>, forKeys: <Key_Array>)
      
          //Example
          let dict = NSDictionary(objects: ["one","two"], forKeys: ["1","2"])
      

      【讨论】:

        【解决方案4】:
        let keyArray = [1,2,3,4]
        let objectArray = [10, 20, 30, 40]
        let dictionary = NSMutableDictionary(objects: objectArray, forKeys: keyArray)
        print(dictionary)
        

        输出:-

        {
          4 = 40;
          3 = 30;
          1 = 10;
          2 = 20;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-05
          • 1970-01-01
          • 1970-01-01
          • 2016-05-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多