繁体   English   中英

SwiftUI:! [Array] 编译器无法在合理的时间内对该表达式进行类型检查

[英]SwiftUI:! [Array] the compiler is unable to type-check this expression in reasonable time

你能帮我解决这个问题吗? 问题出在文本代码中带有字符串数组的第二个按钮中,如果文本代码中有字符串数组,则标记典型错误:“编译器无法在合理的时间内对该表达式进行类型检查”,但如果我把字符串数组改成普通字符串,没有错误。 如果 sti 数组中有 2 个或更多元素以及第二个元素,则只会出现第二个按钮。

Group {
    let telephone = "tel://"
    
    Button(action:{
        let formattedString = telephone + CardPn[0]
        guard let url = URL(string: formattedString) else { return }
        UIApplication.shared.open(url)
    }){
        Text(CardPn[0])
            .fontWeight(.bold)
            .underline()
    }
    
    if CardPn.count >= 2{
        Button(action:{
            let formattedString = telephone + CardPn[1]
            guard let url = URL(string: formattedString) else { return }
            UIApplication.shared.open(url)
        }){
            Text(CardPn[1])
                .fontWeight(.bold)
                .underline()
        }
    }
}

修复the-compiler-is-unable-to-type-check-this-expression-in-reasonable-time一般建议:

  • 为变量使用显式类型:
let telephone = "tel://"   // Not Optimal

let telephone: String = "tel://"    // This is Better because of the explicit `: String`
  • 使用较小的声明而不是包含所有逻辑的一件大事:
var body: some View {
    
    // Not optimal button
    Button(action: {
    // do something
        .
        .
        .
    }, label: {
        Text("something")
            .
            .
            .
    })
    

    // Better example of a button
    Button(action: actionOfTheButton, label: buttonLabel)

}

// Declare the action somewhere else
func actionOfTheButton() {
    // do something
        .
        .
        .
}

// Label of the button is declared here
var buttonLabel: some View {
    Text("something")
        .
        .
        .
}
  • 避免在一个变量中进行大计算:
// We want to calculate the finalArea

// some variables to showcase
let someWidth: CGFloat = 200
let someHeight: CGFloat = 450
let ratio: CGFloat = 0.75
let maxSize: CGFloat = 80000
let minSize: CGFloat = 100

// not optimal because there are lots calculations going on in one line
// to calculate the finalArea
let finalArea = max(min((someWidth * someHeight) * ratio, minSize), maxSize)

// this approach is better, both for compiler and for code-readability,
// finalArea is calculated in 3 steps instead of 1:
let initialArea = someWidth * someHeight
let areaWithRatio = initialArea * ratio
let finalArea = max(min(areaWithRatio, minSize), maxSize)
  • 确保你没有太大的东西。 例如,一个包含 5000 行元素的数组可能会让编译器抱怨。

  • 我记得的最后一种可能性是您有语法错误或其他错误。
    在这种情况下,您应该尝试着眼于问题并解决它。

你不需要 go all-in 来声明显式类型,因为这是 Swift 语言的一个不错的特性,你不想把它扔掉,但事实上,这总是有助于编译器.

关于第二个技巧,通常建议将您的应用程序切割成更小的组件而不是大组件。 这也有助于您的代码更具可读性和更易于管理。 您的项目越大,您就越感谢自己为这些较小的组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM