Cannot use string interpolation for arrays in SwiftUI.Text initializer

I've encountered quite a weird error when using string interpolation within SwiftUI.
Consider this code :

struct MyView: View {
  let array: [String] = ["Hello", "World"]
  var helper: String { return "\(array)" }

  var body: some View {
    Text("\(array)") // doesn't work
    Text(helper) // works 

The offending line complains that Instance method 'appendInterpolation(_:formatter:)' requires that '[String]' inherit from 'NSObject'

If I use a simple type, like Text("\(someInteger)") then this works just fine.

I'd have expected for Text("\(array)") to work, simply by interpolating the String first and the using the result to initialize Text.

Does anyone know what's going on here and why string interpolation works "different" here?

This should work: Text(String("\(array)"))

The reason is – there are different initialisers at play here:

// uses:
public init<S>(_ content: S) where S : StringProtocol


// uses:
public init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)

where LocalizedStringKey conforms to ExpressibleByStringInterpolation protocol.

IIUC this is done to support localisation out of the box. Somewhat non obvious but that's the way it is.

1 Like

Ok, I guess I kinda understand this.
From what I see StringProtocol also inherits from ExpressibleByStringInterpolation so technically both initializers "fit" here I guess.

It's just really weird that direct interpolation works for some types and doesn't work for others.