【问题标题】:Swift CoreData DictionaryResultType castSwift CoreData DictionaryResultType 转换
【发布时间】:2014-06-26 21:06:05
【问题描述】:

在以下代码中,我使用 CoreData 来获得不同的结果:

    request.propertiesToFetch = NSArray(objects: "docID", "docName")
    request.resultType = NSFetchRequestResultType.DictionaryResultType
    request.returnsDistinctResults = true

    var distinctResults: NSArray = context.executeFetchRequest(request, error: nil)
    println(distinctResults)

这是 println() 的输出:

( { 文档ID = 3; docName = "高伊博士"; }, { 文档ID = 1; docName = "巴博士"; }, { 文档ID = 0; docName = "符博士"; }, { 文档 ID = 2; docName = "巴兹先生"; } )

这是一个带有字典的数组 - 我如何将这个 NSArray 转换为带有 for 循环的字典

感谢您的帮助!

【问题讨论】:

  • 您希望字典采用什么格式?
  • 对不起 - 我想转换成 Dictionary

标签: objective-c xcode core-data swift


【解决方案1】:

NSArray 可以用作 Array,它更复杂,因为您的响应结构不是 Array<Dictionary<Int,String>>,而是真正的 Array<Dictionary<String,Any>>,其中 Any 是 docName 的 String,但 docID 的 int。

var dict = Dictionary<Int, String>()
for nsdict in distinctResults as Array<NSDictionary> {
    let docId = nsdict.valueForKey("docID") as? NSNumber as? Int
    let docName = nsdict.valueForKey("docName") as? String

    if docId && docName {
        dict[docId!] = docName!
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多