0
votes

Alright, so I have a tic tac toe game here, and my app was crashing at a specific line in my isOccupied func because, as the error indicated, one of my optionals was equalling nil, which was screwing with everything else.

So I fixed the exception with an if-else statement, however the else return part really doesn't make much sense in my app. I only need the function to return what is returned in the if part, which is Bool(plays[spot]!) so that the rest of the program knows that a certain spot has been taken. Returning true or false (because its a bool) doesn't make sense, and I can't return Bool(plays[spot]!) obviously, so what do I do?

As it is, when I click one of the spaces, no X appears and O just appears in the center spot. Always. The code block:

func isOccupied(spot:Int)->(Bool) {
        if let doesPlay = plays[spot] {
        return Bool(plays[spot]!)
        }
        else {
            return false
        }
    }
2
What is plays? Is an array of booleans? If so then it sounds like you should fully initialise it to false at the start of the game. Then you can return plays[spot]! - however what you have looks OK too - it returns false if the spot isn't occupied (presumably that is what a nil in plays[spot] means) - Paulw11
Is isOccupied supposed to return which player occupies the spot? i.e. it should return 3 possible values, empty, X, or O? - Mike S
@Paulw11 In my code: var plays = Dictionary<Int,Int>() Yeah, that was what I was thinking. But it doesn't work. I'll try initializing it as false - skyguy
@Mike S No, it is just supposed to return a boolean of if a space is occupied (true) or if its free (false), regardless of player. - skyguy
@user3781199 Ok, just so I'm clear, what that code is doing is looking up spot in plays and, if it exists, it returns true/false depending on that value. If spot doesn't exist in plays it returns false. This makes sense to me since if spot doesn't exist in plays, then that spot obviously isn't occupied. Are you sure that this is where the problem is? You said that clicking on a space always produces O in the center, what does the code for that look like? - Mike S

2 Answers

0
votes

Change it to this:

func isOccupied(spot : Int) -> (Bool) {
    if plays[spot] == nil {
        return false
    } else {
        return true
    }
}
0
votes

This will also work, both are essentially the same...

    func isOccupied(spot:Int) -> Bool { 
            if plays[spot] != nil {
                return true
            }
            return false
}