Eric Conner
Eric Conner

Reputation: 10752

Array to String in Swift, stringInterpolationSegment

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?

Upvotes: 4

Views: 3729

Answers (2)

Airspeed Velocity
Airspeed Velocity

Reputation: 40963

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.

Upvotes: 1

vacawama
vacawama

Reputation: 154631

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

Upvotes: 3

Related Questions