SwiftUI 应用程序不断崩溃可能是由于 ForEach

SwiftUI app keeps crashing probably due to ForEach

我试图使用 SwiftUI 创建井字游戏,但每当我尝试将代码获取到 运行 时,模拟器就会崩溃。这是我的代码:

import SwiftUI

struct ContentView: View {
    @State private var allMarks: Array? = [nil, nil, nil, nil, nil, nil, nil, nil, nil]
    var body: some View {
        HStack(content: {
            ForEach(1..<3) { i in
                VStack(content: {
                    ForEach(1..<3) { i in
                        ZStack(content: {
                            RoundedRectangle(cornerRadius: 12.0, style: .continuous)
                                .aspectRatio(contentMode: .fit)
                                .foregroundColor(Color(UIColor.systemGroupedBackground))
                                .onTapGesture {
                                    if allMarks?[i] == nil {
                                        allMarks?[i] = "circle"
                                        var randomCell = allMarks?.randomElement()
                                        repeat {
                                            randomCell = allMarks?.randomElement()
                                        } while randomCell == nil
                                        randomCell = "xmark"
                                    }
                                }
                            Image(systemName: allMarks?[i] as! String)
                        })
                    }
                })
            }
        })
    }
}

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

我尝试删除 ForEach 并粘贴 ZStack 的内容两次,然后再次粘贴 ZStack 两次但没有崩溃,所以我认为它是 ForEach 导致了问题。我不确定,因为它也崩溃了几次,即使在我完全删除 ForEach 之后也是如此。任何人都可以帮我找出问题所在以及我可以做些什么来解决它吗?

这就是导致您的代码崩溃的原因:

Image(systemName: allMarks?[i] as! String)

您正在向下转换 returns nil 的可选值。

要解决此问题,您需要先确保该值为 String,然后您才能在 Image 视图中安全地使用它。

因此将其更改为:

if let imageName = allMarks?[i] as? String {
    Image(systemName: imageName)
}

更多信息,结帐https://developer.apple.com/swift/blog/?id=23

使用以下代码更改您的图片,因为您试图解包 nilas! String 以致应用程序崩溃。如果您定义它可能是 nil 并给出未分配给任何 SF 符号的默认值 String,它将为空。

Image(systemName: allMarks?[i] as? String ?? "")