The correct syntax of a for loop is:
for [VARIABLE_NAME] in [SEQUENCE] {
}
In this case it could be
for i in 0...(firstArray.count - 1) { }
or
for i in 0..<firstArray.count { }
To merge both arrays, you could do:
let firstArray = ["John", "Sam"]
let secondArray = ["Smith",]
var names = zip(firstArray, secondArray).map { $0 + " " + $1 }
If you want to add the rest of the longer array:
if firstArray.count < secondArray.count {
names.append(contentsOf: secondArray[firstArray.count...])
} else if secondArray.count < firstArray.count {
names.append(contentsOf: firstArray[secondArray.count...])
}
print(names) //["John Smith", "Sam"]
Finally, you could join them this way:
let joinedNames = names.joined(separator: " and ") //John Smith and Sam
More generically, you could merge any number of arrays this way:
func zigzag<T>(through arrays: [[T]]) -> [T] {
var result = [T]()
var index = 0
while true {
var didAppend = false
for array in arrays {
if index < array.count {
result.append(array[index])
didAppend = true
}
}
if didAppend == false { break }
index += 1
}
return result
}
For example:
zigzag(through: [[11, 12], [21, 22, 23, 24], [31, 32, 33]])
//[11, 21, 31, 12, 22, 32, 23, 33, 24]