getting "fatal error: NSArray element failed to match the Swift Array Element type" when trying to read values from an array of class objects

Ok, let's start with your error.

fatal error: NSArray element failed to match the Swift Array Element type

A swift array is complaining that one of it's elements is not what it's expecting. The NSArray element does not match the swift array element.

Now we know that a NSArray can store different types of elements, for example, NSNumber, NSDictionary, NSString... you get the picture. So clearly our issue here is type related.

Now looking at your segue code we can see that we do not actually state what type books is, we let swift's type inference work it out for us. This is where our first sign of the issue occurs. You are expecting an array of [Book] but for some reason you are getting a type of NSArray.

If you make the change from:

let books = categoryStore.allCategories[selectedIndexPath.row].books
let books : [Book] = categoryStore.allCategories[selectedIndexPath.row].books

You will now crash at this line, because you are now stating the type expected.

Full Method:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ShowBook" {
        if let selectedIndexPath = tableView.indexPathForSelectedRow {
            let books : [Book] = categoryStore.allCategories[selectedIndexPath.row].books

            let destinationVC = segue.destinationViewController as! BookViewController
            destinationVC.books = books
        }
    }
}

This is backed up by your debugger console output, it says that you have an array of 13 NSDictionary types.

This means you need to investigate where you populate the [Book] array - i.e. categoryStore.allCategories

Tags:

Ios

Swift

Swift2