我正在阅读一些有关 Swift 5 的字符串插值的资源,并在 Playground 中试用它。我成功地组合了两个单独的 String
,但我对如何组合 String
的 Array
感到困惑。
这是我所做的...
String(stringInterpolation: {
let name = String()
var combo = String.StringInterpolation(literalCapacity: 7, interpolationCount: 1)
combo.appendLiteral("Sting One, ")
combo.appendInterpolation(name)
combo.appendLiteral("String Two")
print(combo)
return combo
}())
如何使用 String
的 Array
做这样的事情?
最佳答案
目前还不清楚这与插值有什么关系。可能对什么是字符串插值有误解?如果目标是将字符串数组连接成单个逗号分隔的字符串,只需继续将字符串数组连接成单个字符串即可:
let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s // "Manny, Moe, Jack”
如果要点是数组元素类型未知但可以用字符串表示,则通过 String(describing:)
进行映射:
let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s // "1, 2, 3”
关于arrays - String.init(stringInterpolation :) with an array of strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55225772/