Search code examples
iosswiftexc-bad-access

Why is an optional in Swift giving me EXC_BAD_ACCESS?


I have the following code:

// Get the matches
var recipieMatches = queryResults[MATCHES_INDEX] as Array<Dictionary<String, AnyObject>>
// Set some global vars
var numberOfRecipiesToDisplay: Int = recipieMatches.count

for i in 0...(numberOfRecipiesToDisplay - 1)
{
    var time:  Int? = ((recipieMatches[i])["totalTimeInSeconds"]) as Int? // THIS LINE
}

I am getting an EXC_BAD_ACCESS error on the line in the for loop.

My Question: How is this possible? I know recipieMatches[i] is a value since the for loop iterates over the count of the array.


Solution

  • as will crash if the value you're extracting isn't the correct type - in this case if it isn't an Int?

    Instead, use optional casting - as?. If the value isn't an Int? then the optional will be nil.