我有两个数组
array1 = ["Fri","Sat","Sun"]
array2 = ["5","6","7"]
现在我要创建一个newArray:["Fri5", "Sat6", "Sun7"]
。怎么做?提前谢谢。
答案 0 :(得分:7)
对于功能方法,请使用map
和let array1 = ["Fri","Sat","Sun"]
let array2 = ["5","6","7"]
let result = zip(array1, array2).map { $0 + $1 }
print(result)
:
["Fri5", "Sat6", "Sun7"]
输出:
zip
[("Fri", "5"), ("Sat", "6"), ("Sun", "7")]
创建一系列元组map
和String
,然后通过获取每个元组并将两个String
合并为一个fetch
来创建最终数组}。
答案 1 :(得分:0)
你也可以试试这个:
var array1 = ["Fri","Sat","Sun"]
var array2 = ["5","6","7"]
var array3 = array1.map{ $0 + (array2[array1.indexOf($0)!]) } // ["Fri5", "Sat6", "Sun7"]
答案 2 :(得分:-1)
使用Swift 4.2,您可以使用以下五个Playground示例之一来解决您的问题。
sequence(state:next:)
let array0 = ["Fri", "Sat", "Sun"]
let array1 = ["5", "6", "7"]
let unfoldSequence = sequence(state: (array0.makeIterator(), array1.makeIterator()), next: { (iterators) -> String? in
guard let string0 = iterators.0.next(), let string1 = iterators.1.next() else { return nil }
return string0 + string1
})
let array = Array(unfoldSequence)
print(array) // prints: ["Fri5", "Sat6", "Sun7"]
zip(_:_:)
和map(_:)
let array0 = ["Fri", "Sat", "Sun"]
let array1 = ["5", "6", "7"]
let array = zip(array0, array1).map({ $0 + $1 })
print(array) // prints: ["Fri5", "Sat6", "Sun7"]
AnyIterator
let array0 = ["Fri", "Sat", "Sun"]
let array1 = ["5", "6", "7"]
var iterator0 = array0.makeIterator()
var iterator1 = array1.makeIterator()
let anyIterator = AnyIterator<String> {
guard let string0 = iterator0.next(), let string1 = iterator1.next() else { return nil }
return string0 + string1
}
let array = Array(anyIterator)
print(array) // prints: ["Fri5", "Sat6", "Sun7"]
reduce(into:_:)
let array0 = ["Fri", "Sat", "Sun"]
let array1 = ["5", "6", "7"]
let array = zip(array0, array1).reduce(into: [String](), { (result, tuple) in
result.append(tuple.0 + tuple.1)
})
print(array) // prints: ["Fri5", "Sat6", "Sun7"]
Sequence
和IteratorProtocol
协议的对象struct StringArrayConcatenatingSequence: Sequence, IteratorProtocol {
let firstArray: [String]
let secondArray: [String]
private var index = 0
init(firstArray: [String], secondArray: [String]) {
self.firstArray = firstArray
self.secondArray = secondArray
}
mutating func next() -> String? {
guard index < Swift.min(firstArray.count, secondArray.count) else { return nil }
defer { index += 1 }
return firstArray[index] + secondArray[index]
}
}
let array0 = ["Fri", "Sat", "Sun"]
let array1 = ["5", "6", "7"]
let sequence = StringArrayConcatenatingSequence(firstArray: array0, secondArray: array1)
let array = Array(sequence)
print(array) // prints: ["Fri5", "Sat6", "Sun7"]