0

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?

4
  • Unclear what the point of the question is. What array are we talking about? What’s the proposed input and desired output? What’s the point of using String.StringInterpolation directly here? Commented Mar 18, 2019 at 16:24
  • Any array will do. I'm just trying to figure out how to combine Strings from the same Array, so the output is one long String. Commented Mar 18, 2019 at 16:35
  • Why do you need interpolation for that? Just join the array (call joined) directly. Commented Mar 18, 2019 at 16:37
  • But then you can use String(describing:) to perform the conversion to a string representation. — However, I would urge you to add all this to the question; as I said, as it stands it is unclear what the point is, and the title “with an array of strings” would seem to be outright wrong. It might even be good just to show the actual JSON. There may be a much simpler way; this could well be an x-y question. Commented Mar 18, 2019 at 16:57

1 Answer 1

1

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”
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.