带有枚举值字符串插值的文本,在调用实例方法时没有完全匹配 'appendInterpolation'

Text with string interpolation of Enum value, No exact matches in call to instance method 'appendInterpolation'

我迷路了,为什么 Text("\(type)") 会同时出现编译错误 Text(str) 却不会。那个字符串插值没有创建字符串吗?

错误请查看下方截图。

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


您需要使用 rawValue,并尝试更有效地循环遍历 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)
        }
    }
}

Xcode 未能检测到应该使用哪个 Text 初始化程序,这是一个相当烦人的错误。

可能的解决方法:

  1. 使用 String(describing:) 初始值设定项:
Text(String(describing: type))
  1. 首先声明一个变量:
let text = "\(type)"
Text(text)