简体   繁体   English

如何检查NSMutableArray元素是NSNull还是AnyObject

[英]how to check if NSMutableArray element is NSNull or AnyObject

I have a PersonsArray: NSMutableArray = [NSNull, NSNull, NSNUll, NSNull, NSNull, NSNUll, NSNull] . 我有一个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. 我需要七个插槽,然后可以将它们作为AnyCore实体CoreData条目填充。

I need to do a for in loop on this NSMutableArray... 我需要在此NSMutableArray上进行for in循环...

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. 如果索引槽是NSNull,我想传递到下一个索引槽,如果索引槽中装有我的对象,我想在该对象上执行代码。


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. 注意:使用NSNull只是NSMutableArray中的占位符,因此其计数始终为7,我可以用Object替换任何(7)插槽。 Should I be using something other than NSNull as my placeholder? 我是否应该使用NSNull以外的其他字符作为占位符?

NSNull() is a singleton object, therefore you can simply test if the array element is an instance of NSNull : NSNull()是一个单例对象,因此您可以简单地测试数组元素是否为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. 对空插槽使用nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM