如何在swift

时间:2017-10-09 20:33:24

标签: arrays swift dictionary

let arra = ["abc","def","abc","def"]
let arra2 = ["addr1","addr2","addr1","addr2"]

预期产出

dic = ["abc":"addr1","addr1" , def: "addr2","addr2"]

5 个答案:

答案 0 :(得分:2)

Swift 4的新词典初始化程序可以让您轻松完成这类工作:

let arra = ["abc","def","abc","def"]
let arra2 = ["addr1","addr2","addr1","addr2"]

let dict = [String:[String]](zip(arra,arra2.map{[$0]}),uniquingKeysWith:+)

print(dict) // ["abc": ["addr1", "addr1"], "def": ["addr2", "addr2"]]

[编辑] Swift 3当量:

var dict : [String:[String]] = [:]
zip(arra,arra2.map{[$0]}).forEach{ dict[$0] = (dict[$0] ?? []) + $1 }

答案 1 :(得分:0)

使用zip(_:_:)reduce(_:_:)

let array1 = ["abc", "def", "abc", "def"]
let array2 = ["addr1", "addr2", "addr1", "addr2"]

let dictionary = zip(array1, array2).reduce([String: String]()) {
  var dictionary = $0

  dictionary[$1.0] = $1.1

  return dictionary
}

print(dictionary) // ["abc": "addr1", "def": "addr2"]

答案 2 :(得分:0)

应该有更简单的方法,但总的来说:

import UIKit

let keyArray = ["abc","def","abc","def"]
let valueArray = ["addr1","addr2","addr1","addr2"]

let setFromKeyArray = Set(keyArray)

var finalDict = [String: [String]]()
for index in 0..<keyArray.count {
    if let _ = finalDict[keyArray[index]] {
        finalDict[keyArray[index]]!.append(valueArray[index])
    } else {
        finalDict[keyArray[index]] = [valueArray[index]]
    }
}

print(finalDict)
// output: ["abc": ["addr1", "addr1"], "def": ["addr2", "addr2"]]

答案 3 :(得分:0)

最好的DennisKristijan以及Alain

let arra = ["abc", "def", "abc", "def"]
let arra2 = ["addr1", "addr2", "addr1", "addr2"]

let dict = zip(arra, arra2).reduce([String:[String]]()){
    var d = $0
    d[$1.0] = ($0[$1.0] ?? []) + [$1.1]
    return d
}

print(dict) // ["def": ["addr2", "addr2"], "abc": ["addr1", "addr1"]]

记住词典是无序的。

答案 4 :(得分:0)

您可以使用以下内容:

let arra = ["abc","def","abc","def"]
let arra2 = ["addr1","addr2","addr1","addr2"]

var dictionary: [String: String] = [:]
dictionary.merge(zip(arra, arra2)) { (old, new) -> String in
    return "\(old), \(new)"
}

print(dictionary)

输出:

["abc": "addr1, addr1", "def": "addr2, addr2"]