如何在Swift中合并两个数组

时间:2018-04-08 10:10:56

标签: arrays swift merge zip

我有两个阵列。

let A = ["91","91","49"]
let B = ["9989898909","9089890890","9098979896"]

我需要合并这些数组并在下拉列表中显示为

["91 9989898909","91 9089890890","49 9098979896"]

如何使用swift获取此结果。我是swift的新手,有人可以帮忙解决这个问题。

3 个答案:

答案 0 :(得分:12)

压缩数组并连接结果:

let A=["91","91","49"]
let B=["9989898909","9089890890","9098979896"]
let zipped = zip(A, B)
let result = zipped.map { $0.0 + " " + $0.1 }

答案 1 :(得分:1)

这是Swift中的一个片段:

let a = ["90", "91", "92"]
let b = ["80012", "82379", "123712"]

let result: [String] = a.enumerated().map { (index, element) in
    return index < b.count ? element + " " + b[index] : element
}

答案 2 :(得分:1)

let A = ["91","91","49", "5"]
let B = ["9989898909","9089890890","9098979896"]

使用zip()加入数组AB的值。如果AB具有不同数量的元素,则加入仍然有效。然后map从压缩结果数组到那些在它们之间有空格的元素的元组

let C : [String] = zip(A,B).map {$0 + " " + $1}