Bhavani chada
Bhavani chada

Reputation: 61

How to merge two arrays in Swift

I have two arrays.

let A = ["91","91","49"]
let B = ["9989898909","9089890890","9098979896"]

I need to merge these arrays and show it in the dropdown as

["91 9989898909","91 9089890890","49 9098979896"]

How can I get this result using swift.Im newbie to swift,can anyone please help on this.

Upvotes: 4

Views: 6403

Answers (3)

ielyamani
ielyamani

Reputation: 18581

let A = ["91","91","49", "5"]
let B = ["9989898909","9089890890","9098979896"]

Use zip() to join values from both arrays A and B. If A and B have a different number of elements, the joining would still work. then map the tuples from the zipped result array to those elements with a space between them

let C : [String] = zip(A,B).map {$0 + " " + $1}

Upvotes: 1

Aryan
Aryan

Reputation: 57

here is a snippet in Swift:

let a = ["90", "91", "92"]
let b = ["80012", "82379", "123712"]

let result: [String] = a.enumerated().map { (index, element) in
    return index < b.count ? element + " " + b[index] : element
}

Upvotes: 2

Gereon
Gereon

Reputation: 17844

Zip the arrays and concatenate the results:

let A=["91","91","49"]
let B=["9989898909","9089890890","9098979896"]
let zipped = zip(A, B)
let result = zipped.map { $0.0 + " " + $0.1 }

Upvotes: 15

Related Questions