for 循环的正确语法是:
for [VARIABLE_NAME] in [SEQUENCE] {
}
在这种情况下,它可能是
for i in 0...(firstArray.count - 1) { }
或
for i in 0..<firstArray.count { }
要合并两个数组,您可以这样做:
let firstArray = ["John", "Sam"]
let secondArray = ["Smith",]
var names = zip(firstArray, secondArray).map { $0 + " " + $1 }
如果要添加更长的数组的其余部分:
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"]
最后,你可以这样加入他们:
let joinedNames = names.joined(separator: " and ") //John Smith and Sam
更一般地说,您可以通过这种方式合并任意数量的数组:
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
}
例如:
zigzag(through: [[11, 12], [21, 22, 23, 24], [31, 32, 33]])
//[11, 21, 31, 12, 22, 32, 23, 33, 24]