2

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?

4

1 回答 1

5

NSNull()是一个单例对象,因此您可以简单地测试数组元素是否是一个实例NSNull

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

或使用“相同于”运算符:

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

或者,您可以使用一组选项:

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

用于nil空槽。

于 2015-04-29T21:33:39.127 回答