skip to Main Content

I was trying to create a Tic-Tac-Toe game using SwiftUI, but Simulator crashes whenever I try to get the code to run. Here’s my code:

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()
    }
}

I tried removing ForEach and pasting the contents of the ZStack other two times and then pasting said ZStack again twice and it didn’t crash, so I assume it’s ForEach that caused the problem. I’m not sure thought as it crashed a few times, too, even after I completely removed ForEach. Can anyone help me figure out what’s wrong and what I could do to fix it?

2

Answers


  1. This is what causes your code to crash:

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

    You’re downcasting an optional value that returns nil.

    To resolve this you need to make sure the value is a String first and then you can use it safely in your Image view.

    So change that to:

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

    More information, checkout https://developer.apple.com/swift/blog/?id=23

    Login or Signup to reply.
  2. Change your Image with below code, because you try to unwrap a nil value as! String so that App crashes. If you define it may be nil and give a default String that isn’t assigned to any SF Symbol, it will be empty.

    Image(systemName: allMarks?[i] as? String ?? "")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search