1

since I update the xcode 10.1, this error occur.

The code is:

class mainPageJobObj   {
    var _id : String = ""
    var avatar :String = ""
    var name : String = ""
    var serviceState = ""
}
items : [mainPageJobObj]!
items // i read it from server and its not empty
let oneItem = items[index] // Fatal error: NSArray element failed to match the Swift Array Element type -- This is what compiler is showing.

after debuging debuging more specefic

15
  • The short answer is that items doesn't contain instances of mainPageJobObj. You need to show readItemsFromServer for a better answer Commented Apr 7, 2019 at 9:02
  • ReadItemsFromServer() is not returning the array of mainPageJobObj here. Commented Apr 7, 2019 at 9:05
  • actually i read it from server it before and i dont use this class but for simplicity i put this class in declaration. i debug it and its not empty! Commented Apr 7, 2019 at 9:07
  • 1
    You can see from your debug screenshot that items is an array of dictionaries, not an array of mainPageJobObj Commented Apr 7, 2019 at 9:33
  • it is very hard to understand the issue when you have posted only fragments of your code. Commented Apr 7, 2019 at 9:40

1 Answer 1

2

The error message tells you that items was bridged from an NSArray (which does not enforce typing of its elements) but when Swift tried to retrieve an element, it did not find an instance of mainPageJobObj, which is what you said they array contained.

From the debug screen shot you can see that the items array actually contains instances of NSMutableDictionary.

A quick fix is to use the appropriate declaration of items:

var items:[String:Any] = slider.mainPageObj.items!
let oneItem = items[index]
let name = oneItem["name"]

A much better fix is to use Swift types from the start; If the data from your server is being returned in JSON format then use Codable to create Swift Struct or Class instances.

Sign up to request clarification or add additional context in comments.

3 Comments

the data from server is parsed from dic to [mainPageJobObj] by EVReflection ( github.com/evermeer/EVReflection ),i want the items type be [mainPageJobObj] not a dic! it works before updating xcode!
I don't know anything about EVReflection or what might have changed - You have been asked repeatedly to show the code that fetches your data and creates the array. What I can tell you is that you have an array of dictionaries and that is causing your crash. BTW Xcode 10.2 is now released
man you sure saved me! with the update to xcode 12.4 i had a similar problem with MLVision, but your approach was an excellent solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.