Ben Ben - 4 months ago 10
Swift Question

Check if an Object in a Dictionary is an Int (Swift)

I'm relatively new to coding iOS and have not fully wrapped my head around optionals, downcasting, dictionaries and related fun concepts. I would greatly appreciate help on the following.

I am downloading data from a database and want to perform checks on the data to avoid a crash. In this particular case I want to check if an Object in a dictionary is an Int before performing a task to avoid a crash.

//The downloaded dictionary includes Int, Double and String data
var dictionaryDownloaded:[NSDictionary] = [NSDictionary]()

//Other code for downloading the data into the dictionary not shown.

for index in 1...dictionaryDownloaded.count {

let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]

if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil {
self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
}

self.recommendationsArray.append(currentlyConstructingRecommendation)
}


I followed the approach from this related question and answer. However, the problem is the "if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil" line never is never true. I believe that is because the value is an optional object. I tried adjusting the dictionary to be of type [String:AnyObject] but that did not have an impact.

I'm stuck and any ideas you have would be appreciated. Please let me know if there is any more detail that is helpful. Thanks!

Answer

With this code: jsonDictionary["SUNDAY OPEN TIME"] as? [Int], you are trying to convert the value to Array<Int>, not an Int.

And in your code, you have another flaw: index in 1...dictionaryDownloaded.count. This causes Index out of range exception, when index gets to dictionaryDownloaded.count.

So, a quick fix would be:

for index in 0..<dictionaryDownloaded.count {

    let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]

    if (jsonDictionary["SUNDAY OPEN TIME"] as? Int) != nil {
        self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
    }

    self.recommendationsArray.append(currentlyConstructingRecommendation)
}

But I recommend you to do it in a more Swifty way.

for jsonDictionary in dictionaryDownloaded {

    if let sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as? Int {
        self.currentlyConstructingRecommendation.sundayOpenTime = sundayOpenTime
    }

    self.recommendationsArray.append(currentlyConstructingRecommendation)
}
Comments