user11209999
user11209999

Reputation:

String.init(stringInterpolation:) with an array of strings

I was reading over some resources about Swift 5's String Interpolation and was trying it out in a Playground. I successfully combined two separate Strings but I am confused about how to combine an Array of Strings. Here's what I did ...

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
}())

How would you do something like this with an Array of Strings?

Upvotes: 0

Views: 436

Answers (1)

matt
matt

Reputation: 535411

It’s unclear what this is supposed to have to do with interpolation. Perhaps there’s a misunderstanding of what string interpolation is? If the goal is to join an array of strings into a single comma-separated string, just go ahead and join the array of strings into a single string:

let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s  // "Manny, Moe, Jack”

If the point is that the array element type is unknown but is string-representable, map thru String(describing:) as you go:

let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s  // "1, 2, 3”

Upvotes: 1

Related Questions