Passing "flattened array" to Any

Is there any way I can pass an array to a variadic function such that the array will be as if each element was passed as a separate parameter? e.g.:

let s: [String]()

Instead of printing this:

["one", "two", "three"]

I want this:

one two three

(Probably a spelling mistake, but your example doesn't compile; replace let with var and : with =.)

It's currently not possible to override Array's conformance to CustomStringConvertible. You could (1) create a wrapper struct (see here for an example) or (2) extend Array with an instance property that is different from description (to avoid ambiguity):

extension Array where Element == String { 
  public var customDescription: String { 
    return self.joined(separator: " ")

// ["one", "two", "three"]

// one two three

(I'm not completely sure if this answers your question.)

Yeah, my example was just written in to the message, not taken from source that actually compiles.
I will ponder your idea. Thank you.

So really I can just forget print altogether (I was just using it with the to: option to "print to a string) I can just do (in my case):

return s.joined(separator: " ").

Thanks. Some day I'll have the entire Swift ecosystem memorized. :slight_smile:

Ah, now your question makes sense.

You could also append Strings to an existing String using +=(_:_:):

var s = "one"

s += " two"
s += " three"

// one two three

This is a mutating operator that adds a String to an existing String (note the use of var). Downside is that you'll have to add the spaces yourself.

joined(separator:) is more elegant in this case. :+1:

Yeah, I wanted to avoid making the spaces explicit, so joined is good for me. I don't even need to specify the separator argument, since it is the default. :green_heart:

1 Like