Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift CoreData DictionaryResultType cast

in the following code I use CoreData to get distinct results:

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

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

This is the output of println():

( { docID = 3; docName = "Dr. Goy"; }, { docID = 1; docName = "Dr. Bar"; }, { docID = 0; docName = "Dr. Foo"; }, { docID = 2; docName = "Mr. Baz"; } )

It's an Array with Dictionaries - How I can cast this NSArray into a Dictionary with a for loop

Thanks for help!

like image 403
Maxim Avatar asked Oct 01 '22 11:10

Maxim


1 Answers

An NSArray can be used as an Array, it's more complicated because the structure of your response isn't Array<Dictionary<Int,String>>, it's really Array<Dictionary<String,Any>> where Any is String for docName, but int for docID.

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!
    }
}
like image 183
David Berry Avatar answered Nov 15 '22 10:11

David Berry