【问题标题】:Cannot convert the expression's type 'NSDictionary' to type 'StringLiteralConvertible'无法将表达式的类型“NSDictionary”转换为类型“StringLiteralConvertible”
【发布时间】:2014-10-21 11:27:26
【问题描述】:

我在创建 NSDictionary 以获取我的 CoreData 模型中的对象时遇到问题。

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'

问题出在字典上。

为什么我不能强制转换字符串来获取对象?有什么解决办法吗?

【问题讨论】:

    标签: ios string core-data swift nsdictionary


    【解决方案1】:

    我认为titlefireDate 是可选属性——如果是,这就是原因。 NSDictionary 不能存储 nil 值。

    您应该:

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

    如果你的 Notificatie 类是这样的:

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

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

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

    如果您选择使用 swift 字典:

    let notDict: [String:AnyObject?] = ["title":notificatie.title, "fireDate": notificatie.fireDate]
    

    【讨论】:

    • 嗯...不确定您对可选属性的含义。我怎么能改变呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多