【问题标题】:'failed to produce diagnostic for expression' error on var body: some View in SwiftUI Xcode 13.2var body 上的“无法为表达式生成诊断”错误:SwiftUI Xcode 13.2 中的一些视图
【发布时间】:2022-01-08 22:25:22
【问题描述】:

我是 SwiftUI 和 Xcode 13.2 的新用户。我正在学习关于 Udemy 的课程,但是当出现“无法为表达式生成诊断;请提交错误报告 (https://swift.org/contributing/#reporting-bugs) 并包含该项目”的错误时遇到了障碍。上面写着var body: some View {}。这是完整的代码。

import SwiftUI

struct ContentView: View {
    
    @State var userText:String = ""
    @State var mode:Int = 1
    
    var body: some View {
        VStack {
            if mode == 1 {
                Text(userText.capitalized())
                    .font(.largeTitle)
            } else if mode == 2 {
                Text(userText.lowercased())
                    .font(.largeTitle)
            } else {
                Text(userText.uppercased())
                    .font(.largeTitle)
            }
        }
        TextField("Enter text here...", text: $userText)
            .background(Color.yellow)
            .padding()
        Text(userText)
            .font(.largeTitle)
        HStack{
            Button(action: {mode = 1}) {
                RoundedButton(text: "Capitalize", color: .green)
                    .padding(5)
            }
            Button(action: {mode = 2}) {
                RoundedButton(text: "Lower", color: .blue)
            }
            Button(action: {mode = 3}) {
                RoundedButton(text: "All Caps", color: .red)
                    .padding(5)
            }
            
        }
    }
}

struct RoundedButton: View {
    var text:String
    var color:Color
    var body: some View {
        Text(text)
            .bold()
            .frame(maxWidth:.infinity)
            .padding()
            .background(color)
            .foregroundColor(.black)
            .cornerRadius(10)
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .previewInterfaceOrientation(.portrait)
    }
}

我该如何解决这个问题?

【问题讨论】:

  • 逐行注释掉,一般是拼写错误。

标签: swift xcode error-handling swiftui xcode13


【解决方案1】:

问题与您的第一个 if 条件中的条件有关。

Text(userText.capitalized())

SwiftUI 不喜欢使用.capitalized()

在您的第三个条件中,您使用的是.uppercased()。也许这就是你想要使用的?

要回答这个问题,解决这个问题的方法是删除.capitalized()

【讨论】:

    【解决方案2】:

    函数capitalized()是swift中不存在的函数。 但是有一个capitalized(with locale: Locale?) 看到这个文档 https://developer.apple.com/documentation/foundation/nsstring/1414023-capitalized 解释一下。

    要将字符串大写,可以使用方法capitalized,例如theString.capitalized。没有结尾()

    所以你得到的错误是由于使用了一个不存在的函数。将 capitalized() 替换为 capitalized 即可解决您的错误。

    在您的代码中使用以下内容来修复您的错误并在文本中大写您的字符串:

     Text(userText.capitalized)
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多