如何对泛型类型进行字符串插值

3

想要传递一个通用类型Value,可以在Text("\(value)"中表示为字符串。

现在,可能唯一的两种数据类型是StringDouble(或其他数字类型),所以我可能会陷入错误的细节之中,因此我希望能听取建议,采用最佳方案。

这里是我尝试做的一个例子。

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'
   }
}
1个回答

6
使用 String(describing:) 方法:
Text("Your answer is \(String(describing: value))")

或者(非常相似):
struct AnswerView<Value: CustomStringConvertible>: View {
   let value: Value
   var body: some View {
    Text("Your answer is \(value.description)")
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接