0

I'm trying to join an array using .joined(separator:). However, I want the separator to include the index. For example, if I have the array ["red", "orange", "yellow", "green"], I want the output to be "red (0), orange (1), yellow (2), green". I tried to do .joined(separator: "\($0.index), "), but that didn't work.

1
  • 1
    Is your output a mistake or do you actually not want the (3) at the end? Commented Jun 17, 2019 at 23:20

2 Answers 2

5

Is this what you want?

let array = ["red", "orange", "yellow", "green"]

let output = array.enumerated()
    .map { $1 + " (\($0))" }
    .joined(separator: ", ")

print(output)   //red (0), orange (1), yellow (2), green (3)

If the last index shouldn't be included, then here is a solution:

let output = (array.dropLast().enumerated()
    .map { $1 + " (\($0))" }
    + [array.last ?? ""])
    .joined(separator: ", ")
Sign up to request clarification or add additional context in comments.

Comments

2

You can try

var arr = ["red", "orange", "yellow", "green"]
let num = (0 ..< arr.count - 1).map { " (\($0)), " }
let res = zip(arr,num).map{ $0 + $1 }.joined() + arr.last!

1 Comment

(0 ..< arr.count - 1) can also be written as arr.indices.dropLast()

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.