Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to string interpolate a generic type

Tags:

swiftui

Looking to pass in a generic type Value that can be represented in a string in a Text("\(value)"

Now literally the only two possible data types would be String and Double ( or some other number type) so maybe I'm going down the wrong rabbit hole here so I'm open for suggestions in the best path to take..

Here is an example of what I'm trying to do..

struct AnswerView<Value: ExpressibleByStringLiteral>: View {
   let value: Value
   var body: some View {
       Text("Your answer is \(value)") //<--Error: No exact matches in call to instance method 'appendInterpolation'
   }
}
like image 647
Sergio Bost Avatar asked May 02 '26 01:05

Sergio Bost


1 Answers

Use String(describing:):

Text("Your answer is \(String(describing: value))")

or (very similarly):

struct AnswerView<Value: CustomStringConvertible>: View {
   let value: Value
   var body: some View {
    Text("Your answer is \(value.description)")
   }
}
like image 119
jnpdx Avatar answered May 05 '26 16:05

jnpdx



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!