Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert the expression's type 'NSDictionary' to type 'StringLiteralConvertible'

I'm having an issue with making a NSDictionary to get the an object in my CoreData Model.

let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
    let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Notificatie), withPredicate: nil, managedObjectContext: moc)

    for notificatie in results
    {
        let singleNotificatie:Notificatie = notificatie as Notificatie

        let notDict:NSDictionary = ["title":notificatie.title, "fireDate":notificatie.fireDate]

    }

Cannot convert the expression's type 'NSDictionary' to type 'StringLiteralConvertible'

The problem is in the Dictionary.

Why can't I cast a String in to get the object? Any solution?

like image 458
SwingerDinger Avatar asked Oct 21 '14 11:10

SwingerDinger


1 Answers

I presume that the title and fireDate are optional properties - if yes, that's the reason. A NSDictionary cannot store nil values.

You should either:

  • store non-nil values only (up to you how, using optional binding, explicitly unwrapped)
  • use a swift dictionary

If this is how your Notificatie class looks like:

class Notificatie {
    var title: String?
    var fireDate: NSDate?
}

using the 1st option you should add to the dictionary only non-nil values:

let notDict:NSDictionary = NSDictionary()

if let title = notificatie.title {
    notDict.setValue(title, forKey: "title")
}

if let fireDate = notificatie.fireDate {
    notDict.setValue(fireDate, forKey: "fireDate")
}

If instead you opt for the swift dictionary:

let notDict: [String:AnyObject?] = ["title":notificatie.title, "fireDate": notificatie.fireDate]
like image 85
Antonio Avatar answered Oct 20 '22 01:10

Antonio