使用变量分隔符连接数组

时间:2019-06-17 22:41:32

标签: arrays swift

我正在尝试使用.joined(separator:)加入一个数组。但是,我希望分隔符包括索引。例如,如果我有数组["red", "orange", "yellow", "green"],则希望输出为"red (0), orange (1), yellow (2), green"。我尝试做.joined(separator: "\($0.index), "),但这没用。

2 个答案:

答案 0 :(得分:4)

这是您想要的吗?

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)

如果不应该包含最后一个索引,则可以采用以下解决方案:

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

答案 1 :(得分:2)

您可以尝试

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!