我试图使用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)
你正在向下转换一个可选值,返回nil
。
要解决这个问题,您需要确保该值首先是String
,然后您可以安全地在Image
视图中使用它。
所以改成:
if let imageName = allMarks?[i] as? String {
Image(systemName: imageName)
}
更多信息,查看https://developer.apple.com/swift/blog/?id=23
用下面的代码更改您的图像,因为您试图打开nil
值as! String
,以便应用程序崩溃。如果你将它定义为nil
,并给出一个没有分配给任何SF符号的默认String
,它将为空。
Image(systemName: allMarks?[i] as? String ?? "")