SashaZ SashaZ - 4 months ago 9
Swift Question

Swift: Dictionary, Remove key and value that are nil

I have a dictionary that a fetch request is returning. This dictionary is then made in to an array of dates from

[String: NSDate]
. This dictionary has a value that is
[:]
. I cannot do anything to remove it. Can anyone help because I have spent two nights trying everything.

let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [[String:NSDate]]
print("results \(results)")
dates = results.map { $0["savedTime"]! as NSDate }


This failed due to the savedTime Key being nil

print result is


[["savedTime": 2016-07-19 23:00:00 +0000], [:]]

Answer

This construct $0["savedTime"]! is wrong. Putting the ! on the object means you know that the object will always be there, but it isn't always there. You are lying to the compiler so it is crashing. Try removing the !.

Also, putting the as NSDate is unnecessary because you already told the compiler that the values are NSDates in the line above. Lastly, since not all the dictionaries have the correct key, you need to remove any that don't. There are a couple of ways to do that, one would be to filter out the nils. Another is to use flatMap which converts and filters out nils at the same time.

Then you end up with the below.

let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [[String:NSDate]]
print("results \(results)")
dates = results.flatMap { $0["savedTime"] }

I'm worried though that even the above, although it compiles and runs, might not be what you really need. The array of dictionaries is a rather odd thing to be pulling out of a managedObjectContext...