我们说我有两个数组:
let letterArray = ["a", "b", "c", "d", "e"...]
let numberArray = [1, 2, 3, 4, 5, 6, 7...]
我想合并两个数组,以便得到
的输出["a1", "b2", "c3", "d4", "e5"]
我将如何做到这一点?
答案 0 :(得分:21)
您可以在map:
之前使用zip(_:_:)
let a = ["a", "b", "c", "d", "e"]
let b = [1, 2, 3, 4, 5]
let result = zip(a, b).map { $0 + String($1) }
print(result) // => ["a1", "b2", "c3", "d4", "e5"]
zip(_:_:)
生成一个自定义Zip2Sequence
,它具有SequenceType
协议的特殊实现,因此它会迭代从两个源集合中生成的对。
答案 1 :(得分:6)
实际上,您可以仅使用map
来执行此操作!
如果两个序列的大小相同,只有enumerate
和map
:
let result = letterArray.enumerate().map { $0.element + String(numberArray[$0.index]) }
如果您不确定哪一个更大,并且您想要使用较小的flatMap
不想要的值进行修剪:
let result = letterArray.enumerate().flatMap {
guard numberArray.count > $0.index else { return .None }
return $0.element + String(numberArray[$0.index])
} as [String]
答案 2 :(得分:1)
zip(_:_:)
将String
数组的元素与Int
数组的元素组合成一个新的String
使用Swift 3,Swift标准库提供zip(_:_:)
功能。 zip(_:_:)
有以下声明:
func zip<Sequence1, Sequence2>(_ sequence1: Sequence1, _ sequence2: Sequence2) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence
创建一系列由两个基础序列构建的对。
要从Zip2Sequence
实例获取新数组,您可以使用Zip2Sequence
的{{3}}方法。下面使用map(_:)
的Playground代码将您的字母和数字元素组合成一个新的String
数组:
let letterArray = ["a", "b", "c", "d", "e"]
let numberArray = [1, 2, 3, 4, 5, 6, 7]
let zipSequence = zip(letterArray, numberArray)
let finalArray = zipSequence.map({ (tuple: (letter: String, number: Int)) -> String in
return tuple.letter + String(tuple.number)
})
print(finalArray) // prints ["a1", "b2", "c3", "d4", "e5"]
您可以使用简洁的样式重构以前的代码:
let letterArray = ["a", "b", "c", "d", "e"]
let numberArray = [1, 2, 3, 4, 5, 6, 7]
let finalArray = zip(letterArray, numberArray).map { $0.0 + String($0.1) }
print(finalArray) // prints ["a1", "b2", "c3", "d4", "e5"]
作为map(_:)
的替代方案,您可以使用Zip2Sequence
的{{3}}方法:
let letterArray = ["a", "b", "c", "d", "e"]
let numberArray = [1, 2, 3, 4, 5, 6, 7]
let zipSequence = zip(letterArray, numberArray)
let finalArray = zipSequence.reduce([]) { (partialResult: [String], tuple: (letter: String, number: Int)) -> [String] in
return partialResult + [tuple.letter + String(tuple.number)]
}
print(finalArray) // prints ["a1", "b2", "c3", "d4", "e5"]
Array
扩展自定义方法将String
数组的元素与Int
数组的元素组合成一个新的String
如果您不想使用zip(_:_:)
,则可以创建自己的Array
扩展方法,以获得预期的结果。下面的Playground代码显示了如何创建它:
extension Array where Element == String {
func mergeLettersWithNumbers(from numberArray: [Int]) -> [String] {
var index = startIndex
let iterator: AnyIterator<String> = AnyIterator {
defer { index = self.index(index, offsetBy: 1) }
guard index < self.endIndex, index < numberArray.endIndex else { return nil }
return self[index] + String(numberArray[index])
}
return Array(iterator)
}
}
let letterArray = ["a", "b", "c", "d", "e"]
let numberArray = [1, 2, 3, 4, 5, 6, 7]
let newArray = letterArray.mergeLettersWithNumbers(from: numberArray)
print(newArray) // prints ["a1", "b2", "c3", "d4", "e5"]