You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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%)。
  • 额外排查步骤:
    1. 执行Product > Clean Build Folder清理项目缓存,重新编译,避免编译器缓存导致的异常。
    2. 若需自定义百分比显示样式(如控制小数位数),可使用PercentFormatStyle配置:
      Text(percentage, format: .percent.precision(.fractionLength(0)))
      

内容的提问来源于stack exchange,提问作者Oliver Park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:52:08