Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolation of a CustomStringConvertible failing in a SwiftUI Text view

Tags:

swift

swiftui

I have roughly something like this and it works (see https://swiftfiddle.com/hu64oaef4fe23e3cqz6fkn44zq):

import Foundation
struct S : CustomStringConvertible {
  var description : String { "foo" }
}
print(S())  // prints foo
print("interpolated \(S())")

But if I try to use the interpolation of the CustomStringConvertible inside a Text view's string, like

var s : S
...
Text("\(s)")

it fails to compile with No exact matches in call to instance method 'appendInterpolation'.

Notably, it compiles and works if I use Text("\(foo.description)"). It also works with things like an Int:

let a = 5
...
Text("\(a)")

Any ideas why the direct interpolation for my CustomStringConvertible type does not work?

Edited: grammar

like image 716
g i i k Avatar asked Oct 21 '25 12:10

g i i k


1 Answers

The Text.init you are using requires some StringProtocol. StringProtocol derives from CustomStringConvertible, not the other way around.

 Text(verbatim: "\(s)")

is an option.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!