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.
2 Answers
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: ", ")
Comments
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
vacawama
(0 ..< arr.count - 1) can also be written as arr.indices.dropLast()
(3)at the end?