how to check if NSMutableArray element is NSNull o

2019-05-25 08:43发布

问题:

I have a PersonsArray: NSMutableArray = [NSNull, NSNull, NSNUll, NSNull, NSNull, NSNUll, NSNull]. I needed seven slots that I then can fill with an Entity CoreData entry as AnyObject.

I need to do a for in loop on this NSMutableArray...

If the index slot is NSNull I want to pass to next index slot, if index slot is filled with my Object I want to execute code on this Object.


example PersonsArray: NSMutableArray = [
    NSNull,
    NSNull,
    NSNull,
    "<iswift.Person: 0x7f93d95d6ce0> (entity: Person; id: 0xd000000000080000 <x-coredata://8DD0B78C-C624-4808-9231-1CB419EF8B50/Person/p2> ; data: {\n    image = nil;\n    name = dustin;\n})",
    NSNull,
    NSNull,
    NSNull
]

Attempting

for index in 0..<PersonsArray.count {
        if PersonsArray[index] != NSNull {println(index)}
}

suggests a bunch of changes that don't work either, like

if PersonsArray[index] as! NSNull != NSNull.self {println(index)}

or

if PersonsArray[index] as! NSNull != NSNull() {println(index)}

NOTE: using NSNull is just a placeholder in NSMutableArray so that its count is ALWAYS 7 and I can replace any of the (7)slots with an Object. Should I be using something other than NSNull as my placeholder?

回答1:

NSNull() is a singleton object, therefore you can simply test if the array element is an instance of NSNull:

if personsArray[index] is NSNull { ... }

or use the "identical to" operator:

if personsArray[index] === NSNull() { ... }

Alternatively, you could use an array of optionals:

let personsArray = [Person?](count: 7, repeatedValue: nil)
// or more verbosely:
let personsArray : [Person?] = [ nil, nil, nil, nil, nil, nil, nil ]

using nil for the empty slots.