2

I'm looking to basically match up two different arrays in Swift using the enumerated method. So if I have:

let array1 = ["a", "b", "c", "d"]
let array2 = ["1", "2", "3", "4"]

I need to return a new array that would read:

newArray = ["1. a1", "2. b2", "3. c3", "4. d4"]

How do I make an array like that?

3
  • 1
    Related: Using “Map” in Swift To Create Superset of Two Arrays Commented Oct 14, 2016 at 13:28
  • 1
    It is not clear where the first digit is coming from. Is it array2[i] or the index? In other words, what should be the result when array2 is ["p", "q", "r", "s"], ["p. ap", "q. bq", "r. cr", "s. ds"] or ["1. ap", "2. bq", "3. cr", "4. ds"]? Commented Oct 14, 2016 at 13:34
  • It would be the latter of the two examples you gave. Commented Oct 15, 2016 at 19:22

3 Answers 3

7

You can use zip method for this:

let res = zip(array1, array2).map {"\($1). \($0)\($1)"}

Note that this approach repeats the item from array2 at the beginning and at the end. If the number at the beginning is supposed to be an index, use this expression instead:

let res = zip(array1, array2).enumerated().map {"\($0+1). \($1.0)\($1.1)"}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to explicitly use the enumerated method on this particular problem.
@tjcarney89 enumerated() by itself operates on a single sequence. zip takes two sequences, and merges them into one. You can use enumerated first, and then grab the index, and apply it to the second sequence, but it is error-prone in situations when the first sequence is longer than the second one.
0

This Solve your problem

let array1 = ["a", "b", "c", "d"]
let array2 = ["1", "2", "3", "4"]
var newArray: [String] = []

for (index, element) in array1.enumerated() {
    newArray.append("\(array1[index]). \(array2[index])\(array1[index])")
}

Comments

0

I managed to figure it out with some help from a friend:

var newArray: [String] = []
    for (index, array1) in array1.enumerated() {
        newArray.append("\(index + 1). \(array1)(\(array2[index]))")
    }
    return newArray

Thanks!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.