arrays - 使用变量分隔符加入数组

标签 arrays swift

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

最佳答案

这是你想要的吗?

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: ", ")

关于arrays - 使用变量分隔符加入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639701/

相关文章:

ios - AudioKit (iOS) - 为频率/振幅变化添加观察者

swift - 尝试在 View Controller 和 TableView Controller 之间传递数据时应用程序崩溃

swift - 遵守协议(protocol)(作为协议(protocol))

ios - Swift 2 JSON POST 请求 [NSMutableURLRequest 的 HTTPBody 的字典与字符串]

PHP:如何处理 SQL 返回值?

c# - 计算数组的频率分布?

c++指针/数组区别

java - 在 jlabel 上使用嵌套循环

javascript - 如何在不使用 key 的情况下将json转换为数组

ios - 如何使用 getObjectInBackgroundWithId 和 saveInBackgroundWithBlock 从 Parse 检索数据