如何将两个数组“合并”在一起? (逐项连接字符串)

时间:2015-03-23 19:42:40

标签: arrays swift

假设我有两个NSString数组:

var firstName = ["Jack", "Sarah", "John"]
var lastName = ["Smith", "Brown", "Doe"]

如何将它们组合成一个看起来像

的数组
var contacts = ["Jack Smith", "Sarah Brown", "John Doe"]

2 个答案:

答案 0 :(得分:7)

您可以使用Zip2(从中创建一系列对 给定的数组)+ map()

let firstName = ["Jack", "Sarah", "John"]
let lastName = ["Smith", "Brown", "Doe"]

let contacts = map(Zip2(firstName, lastName)) { $0 + " " + $1 }

答案 1 :(得分:1)

您可以以各种方式连接字符串,例如:

var firstStr = "Hello"
var secondStr = "World"

var aStr = firstStr + " " + secondStr // Hello World
var bStr = "\(firstStr) \(secondStr)" // Hello World

在你的情况下,你只需要循环一定的时间(例如,数组的长度,但要确保它们都具有相同的长度)。

var firstName = ["Jack", "Sarah", "John"]
var lastName = ["Smith", "Brown", "Doe"]

var contacts : [String] = []

var len = firstName.count

for index in 0..<len {
    contacts.append("\(firstName[index]) \(lastName[index])")
}