'Text with string interpolation of Enum value, No exact matches in call to instance method 'appendInterpolation'
I'm lost, why Text("\(type)") would get compile error meantime Text(str) is not. Did that string interpolation not create a string?
For the error please check screenshot in below.
enum ExpenseType: Codable, CaseIterable {
case Personal
case Business
}
struct AddView: View {
@State private var type: ExpenseType = .Personal
let types: [ExpenseType] = ExpenseType.allCases
var body: some View {
Form {
...
Picker("Type", selection: $type) {
ForEach(types, id: \.self) { type in
let str = "\(type)"
Text(str)
// Compile error
Text("\(type)")
}
}
...
}
Solution 1:[1]
Xcode fails to detect which Text initializer should be used, a rather annoying bug.
Possible workarounds:
- Using
String(describing:)initializer:
Text(String(describing: type))
- Declaring a variable at first:
let text = "\(type)"
Text(text)
Solution 2:[2]
You need to use rawValue, and try to loop more efficiently over the allCases.
enum ExpenseType: String, CaseIterable {
case Personal
case Business
}
struct ContentView: View {
@State var expenseType = ExpenseType.Personal
var body: some View {
List {
Picker(selection: $expenseType, label: Text("Picker")) {
ForEach(ExpenseType.allCases, id: \.self) { type in
Text(type.rawValue)
}
}
.pickerStyle(.inline)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pylyp Dukhov |
| Solution 2 | marc_s |

