无法将表达式的类型'NSDictionary'转换为'StringLiteralConvertible'类型

Swi*_*ger 8 string core-data nsdictionary ios swift

我在使用NSDictionaryCoreData模型中获取对象时遇到问题.

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]

    }
Run Code Online (Sandbox Code Playgroud)

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

问题出在词典中.

为什么我不能将String转换为获取对象?有解决方案吗

Ant*_*nio 8

我认为这是titlefireDate可选属性 - 如果是,那就是原因.A NSDictionary无法存储nil值.

你应该:

  • 仅存储非零值(由您决定如何使用可选绑定显式解包)
  • 使用快速字典

如果这是你的Notificatie班级的样子:

class Notificatie {
    var title: String?
    var fireDate: NSDate?
}
Run Code Online (Sandbox Code Playgroud)

使用第一个选项,您应该只向字典添加非零值:

let notDict:NSDictionary = NSDictionary()

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

if let fireDate = notificatie.fireDate {
    notDict.setValue(fireDate, forKey: "fireDate")
}
Run Code Online (Sandbox Code Playgroud)

相反,如果您选择swift词典:

let notDict: [String:AnyObject?] = ["title":notificatie.title, "fireDate": notificatie.fireDate]
Run Code Online (Sandbox Code Playgroud)