SwiftUI中@State变量报错:Failed to produce diagnostic for expression
解决SwiftUI中"Failed to produce diagnostic for expression"错误
你遇到的这个模糊错误提示,本质是代码中存在多处语法/逻辑问题,导致Swift编译器无法正常生成诊断信息,而非第14行@State private var isLoggedIn = false本身的问题。以下是具体问题修复方案:
1. 子视图未正确接收父视图的绑定变量
ProfileInfoView直接使用$email、$username、$friends,但这些是父视图pp的@State变量,子视图必须通过@Binding接收:
// 修正后的ProfileInfoView struct ProfileInfoView: View { @Binding var email: String @Binding var username: String @Binding var friends: [String] var body: some View { NavigationLink { Friends(email: $email, username: $username, friends: $friends) } label: { Text("friends").foregroundColor(.red) } Spacer() List { Section(header: Text("Account Information")){ HStack{ Text("Email:") Text(email) .font(.body) .padding() } HStack{ Text("Username:") Text(username) .font(.body) .padding() } Button(action: { }) { Text("Logout") .foregroundColor(.red) .font(.headline) .padding() .background(Color.gray.opacity(0.2)) .cornerRadius(10) } .listRowBackground(Color.white) } }.listStyle(.plain) Spacer() } }
同时父视图调用时传递绑定:
// 父视图pp中调用ProfileInfoView的地方 ProfileInfoView(email: $email, username: $username, friends: $friends)
2. 语法错误:Spacer未实例化
在pp视图的Toolbar按钮里,Spacer是类型,需要写成实例Spacer():
// 修正后的Toolbar按钮 ToolbarItem(placement: .navigationBarLeading) { Button(action: { }) { Spacer() // 补充括号 Text("Sign Up") .padding(.bottom) } }
3. 无效颜色值(.r)
Text("friends").foregroundColor(.r)中的.r是笔误,改为.red:
Text("friends").foregroundColor(.red)
4. Text错误使用绑定值
Text($email)和Text($username)不能直接接收Binding类型,改为使用变量本身(因为子视图已经通过@Binding获取了值):
Text(email) // 替代Text($email) Text(username) // 替代Text($username)
5. .background缺少参数
按钮中的.background必须指定背景样式,补充颜色参数:
.background(Color.gray.opacity(0.2)) // 示例颜色,可根据需求调整
6. 未定义的signup视图
EmptyProfileView中调用的signup()视图未在代码中定义,要么补充该视图实现,要么暂时注释掉:
// 暂时注释或补充signup视图实现 // NavigationLink(destination: signup(), label: "sign up")
修复以上所有问题后,编译器即可正常解析代码,那个模糊的错误提示会自动消失。
内容的提问来源于stack exchange,提问作者bil
相关产品推荐
相关产品推荐

