Swift:将两个数组匹配到一个数组中

时间:2016-09-14 02:12:00

标签: arrays swift

我有两个数组

array1 = ["Fri","Sat","Sun"]
array2 = ["5","6","7"]

现在我要创建一个newArray:["Fri5", "Sat6", "Sun7"]。怎么做?提前谢谢。

3 个答案:

答案 0 :(得分:7)

对于功能方法,请使用maplet 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")]创建一系列元组mapString,然后通过获取每个元组并将两个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示例之一来解决您的问题。


#1。使用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"]

#2。使用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"]

#3。使用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"]

#4。使用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"]

#5。创建符合SequenceIteratorProtocol协议的对象

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"]