NSArray element failed to match the Swift Array

NSDictionary array used in the application.


But some items are null.


selectedCategory [NSDictionary] 24 values

[0] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde1

[1] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde2

[2] NSNull * 0x1ef2e5810 0x00000001ef2e5813

[3] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde4

[4] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde5

[5] NSNull * 0x1ef2e5810 0x00000001ef2e5816

[6] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde7

[7] __NSDictionaryM * 3 key/value pairs 0x00000002811ccde8



"selectedCategory[index]"



If the item is null during the query, the program returns an error and closes.


Error Detail : NSArray element failed to match the Swift Array Element type

Expected NSDictionary but found NSNull


I tried all the ways, but I couldn't get the result. What should I do?

Replies

Please show your code. Generally that happens when you cast `Any` (which is `id` in Objective-C) to Swift collection types,

such as `as? [[String: Any]]` or something like that. Without your code, we cannot answer to What should I do?.

Consider this code:

let d = NSDictionary()
let n = NSNull()
let a = NSArray(array: [d, n])
let s = a as! [NSDictionary]
print(s)

It fails on line 4 with the exact the error you’re seeing. The various Objective-C collection types (

NSArray
,
NSDictionary
, and so on) accept any type of elements. In contrast, the equivalent Swift types require that all elements be of one specific type. If you cast the former to the latter, Swift checks the types of the elements to prevent bogus data entering the Swift realm.

In my example, the

NSArray
contains elements of two different types,
NSDictionary
and
NSNull
, and the latter causes Swift to trap.

The best way to avoid this is not work with heterogeneous collections in the first place. If you can’t fix that, you’ll have to unpack the heterogeneous collection very carefully. For example, this code will convert the

NSArray
to a Swift array of optional dictionaries, mapping
NSNull
to
nil
:
let s = a.map { e -> NSDictionary? in
    switch e {
    case is NSNull: return nil
    case let d as NSDictionary: return d
    default: fatalError()
    }
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"