Xcode 14.3.1报错:failed to produce diagnostic for expression求助
问题描述
在Xcode 14.3.1中,按照《100 Days of SwiftUI》教程编写WeSplit项目代码时,出现报错:
failed to produce diagnostic for expression; please submit a bug report
已对照教程视频、ChatGPT等工具检查代码,仍无法解决,且已向Apple提交反馈,寻求可行的修复方案。
出错代码
// // ContentView.swift // WeSplit2 // // Created by Oliver Park on 2023/07/04. // import SwiftUI struct ContentView: View { @State private var checkAmount = 0.0 @State private var numberOfPeople = 2 @State private var tipPercentage = 20 let tipPercentages = [10, 15, 20, 25, 0] var body: some View { NavigationView { Form { Section { TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD")) .keyboardType(.decimalPad) Picker("Number of people", selection: $numberOfPeople) { ForEach(2..<100) { Text("\($0) people") } } } Section { Picker("Tip percentage", selection: $tipPercentage) { ForEach(tipPercentages, id: \.self) { percentage in Text(String(percentage), format: .percent) } } } Section { Text(checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD")) } } .navigationTitle("WeSplit") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
修复方案
- 错误根源:问题出在
Text(String(percentage), format: .percent)这一行。.percent格式化器需要接收数值类型(如Int或Double),但你先将整数percentage转为字符串,再传入格式化构造器,导致Swift编译器无法解析,触发了这个模糊报错。 - 核心修复:将该行修改为:
直接传入Text(percentage, format: .percent)Int类型的percentage,.percent会自动将整数转换为百分比格式(例如20会显示为20%)。 - 额外排查步骤:
- 执行
Product > Clean Build Folder清理项目缓存,重新编译,避免编译器缓存导致的异常。 - 若需自定义百分比显示样式(如控制小数位数),可使用
PercentFormatStyle配置:Text(percentage, format: .percent.precision(.fractionLength(0)))
- 执行
内容的提问来源于stack exchange,提问作者Oliver Park
相关产品推荐
相关产品推荐

