Home > front end >  Text with string interpolation of Enum value, No exact matches in call to instance method 'appe
Text with string interpolation of Enum value, No exact matches in call to instance method 'appe

Time:03-28

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 Bussiness
}

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)")
                    }
                }
                ...
            }


enter image description here

CodePudding user response:

Xcode fails to detect which Text initializer should be used, a rather annoying bug.

Possible workarounds:

  1. Using String(describing:) initializer:
Text(String(describing: type))
  1. Declaring a variable at first:
let text = "\(type)"
Text(text)

CodePudding user response:

You need to use rawValue, and try to loop more efficiently over the allCases.

enum ExpenseType: String, CaseIterable {
    case Personal
    case Bussiness
}

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)
        }
    }
}
  • Related