doc*_*606 8 arrays xcode ios swift
假设我有两个数组:
let letterArray = ["a", "b", "c", "d", "e"...]
let numberArray = [1, 2, 3, 4, 5, 6, 7...]
Run Code Online (Sandbox Code Playgroud)
我想组合两个数组,以便我得到一个输出
["a1", "b2", "c3", "d4", "e5"]
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
Ale*_*ica 22
你可以zip(_:_:)在map之前使用:
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"]
Run Code Online (Sandbox Code Playgroud)
zip(_:_:)生成一个自定义Zip2Sequence,它具有SequenceType协议的特殊实现,因此它迭代从两个源集合中生成的对.
实际上你只能使用map!
如果两个序列的大小相同enumerate,那么map:
let result = letterArray.enumerate().map { $0.element + String(numberArray[$0.index]) }
Run Code Online (Sandbox Code Playgroud)
如果你不确定哪一个更大,你想要使用更小flatMap的不想要的值来修剪:
let result = letterArray.enumerate().flatMap {
guard numberArray.count > $0.index else { return .None }
return $0.element + String(numberArray[$0.index])
} as [String]
Run Code Online (Sandbox Code Playgroud)