4

I am trying to convert an array of enums to a string in Swift. My enum is Printable and has a description property.

I thought this would work:

", ".join(a.map { String($0) }) 

but the compiler complains

Missing argument label 'stringInterpolationSegment:' in call

So, I follow the suggestion,

", ".join(a.map { String(stringInterpolationSegment: $0) })

But I do not understand:

  1. Why is the argument label needed?
  2. What is the type of stringInterpolationSegment?

2 Answers 2

3

You can't call a String initializer with your enum type because there isn't an initializer that takes that type.

There are a number of initializers for String that have the stringInterpolationSegment argument and they each implement it for a different type. The types include Bool, Float, Int, and Character among others. When all else fails, there is a generic fallback:

/// Create an instance containing `expr`\ 's `print` representation
init<T>(stringInterpolationSegment expr: T)

This is the version that is being called for your enum since it isn't one of the supported types.

Note, you can also do the following which is more succinct:

", ".join(a.map { toString($0) })

and you can skip the closure expression (thanks for pointing that out @Airspeed Velocity):

", ".join(a.map(toString))
Sign up to request clarification or add additional context in comments.

1 Comment

You can skip the closure expression: ", ".join(a.map(toString)).
1

As @vacawama points out, the error message is a bit of a red herring, and you can use map and toString to convert it.

But what’s nice is, if you’ve already implemented Printable, then the array’s implementation of Printable will also use it, so you can just do toString(a) to get a similar output.

4 Comments

The OP said his enum is Printable and has a description property.
oops missed that my bad!
This works nicely if you don't mind the enclosing brackets [ and ].
dropLast(dropFirst(toString(a))) (kidding)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.