I have two arrays
array1 = ["Fri","Sat","Sun"]
array2 = ["5","6","7"]
Now I want to create a newArray: ["Fri5", "Sat6", "Sun7"]. How to make it? Thanks in advance.
For a functional approach, use zip and map:
let array1 = ["Fri","Sat","Sun"]
let array2 = ["5","6","7"]
let result = zip(array1, array2).map { $0 + $1 }
print(result)
Output:
["Fri5", "Sat6", "Sun7"]
zip creates a sequence of tuples [("Fri", "5"), ("Sat", "6"), ("Sun", "7")] and map then creates the final array by taking each tuple and combining the two Strings into a single String.
With Swift 5 you can use one of the five following Playground sample codes in order to solve your problem.
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(_:_:) and 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"]
zip(_:_:) and 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"]
AnyIteratorlet 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"]
Sequence and IteratorProtocol protocolsstruct 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"]