1

Though the same question has been asked many a times and the answers were to --> Typecast the array to the required array of class type.

Though i did it typecasting I am still facing the same error with the crash.

Here is my code:

let data = Model.dictArrayFromModel(dict.objectForKey("category_plans")! as! [Model])


public class func dictArrayFromModel(planCategories: [Model]) -> NSArray {

        let jsonArray: NSMutableArray = NSMutableArray()
        for categoryPlans in planCategories {
            jsonArray.addObject(categoryPlans.dictionaryRepresentation())
        }
        for plans in planCategories {
         jsonArray.addObject(plans.dictionaryRepresentation())
         }
        return jsonArray
    }

When i try to use for-in Loop it crashes with the error fatal error: NSArray element failed to match the Swift Array Element type

Inspite of doing the type casting the code is crashing. I do not know what i am missing. Any immediate help will be greatly appreciated.

P.S : The major use case here is I am trying to pass this data the Array or Model to class Model for further processing.

Manju Basha
  • 665
  • 1
  • 9
  • 29
  • Can you show the output of simply `print(dict.objectForKey("category_plans")!)` – Nirav D Jan 05 '17 at 06:04
  • it prints the proper array that is expected. when i checked `dict.objectForKey("category_plans")?.isKindOfClass(NSArray)` it printed `true` too. – Manju Basha Jan 05 '17 at 06:07
  • I have told your to just print `print(dict.objectForKey("category_plans")!)` not some bool condition like `dict.objectForKey("category_plans")?.isKindOfClass(NSArray)`. – Nirav D Jan 05 '17 at 06:14
  • I told u when i print it gives me the expected array as output. – Manju Basha Jan 05 '17 at 06:15
  • What you are printing is `print(data)`, there is no need to initialize for printing, you need to simply add this line of code `print(dict.objectForKey("category_plans")!)` – Nirav D Jan 05 '17 at 06:17
  • I have edited my question with adding the usecase. Please take a look at it and let me know if you can help me with it. – Manju Basha Jan 05 '17 at 06:28
  • This is the last time i'm saying, If you want help then you need to simply show us the output of `print(dict.objectForKey("category_plans")!)` there is no need to initialize anything for that simply add print line in your code and add the console output here in your question. – Nirav D Jan 05 '17 at 06:31
  • Figured out the answer. Thank you @NiravD – Manju Basha Jan 05 '17 at 07:03
  • I think you now got it that `dict.objectForKey("category_plans")!` return array of Dictionary or something else not the array of Model. Glad you solved it. – Nirav D Jan 05 '17 at 07:05

0 Answers0