简体   繁体   English

将非可选的 Any 与 nil 进行比较总是错误的?

[英]Comparing non-optional Any to nil is always false?

I'm iterating through a dictionary of [String: Any]<\/code> , looking for nil<\/code> s, so I can replace them with NSNull<\/code> for a JSON write.我正在遍历[String: Any]<\/code>的字典,寻找nil<\/code> ,所以我可以用NSNull<\/code>替换它们以进行 JSON 写入。 My precompiler warning is telling me that comparing an Any<\/code> to a nil<\/code> will always be false, but I know it contains at least two nils which are never found.我的预编译器警告告诉我,将Any<\/code>与nil<\/code>进行比较总是错误的,但我知道它至少包含两个从未找到的 nil。 Is there a way to check is an Any<\/code> is nil?有没有办法检查Any<\/code>是否为零?

"

An Optional can be nil . Optional 可以是nil Anything else can never be nil .其他任何东西都不能nil An Any is not an Optional. Any不是 Optional。 Thus there is no point comparing an Any to nil .因此,将Anynil进行比较是没有意义的。 The test will never succeed.测试永远不会成功。

If you know that these things might be Optionals, you should have typed this as Any?如果您知道这些东西可能是 Optionals,您应该将其输入为Any? . . That is an Optional and can be compared to nil .这是一个 Optional ,可以与nil进行比较。 Here's a simple example:这是一个简单的例子:

    let s : String? = nil
    let any : Any? = s
    if any == nil {
        print("nil") // nil
    }

As you can see, the test succeeds.如您所见,测试成功。

(Still, if at all possible, it would be even better to type things more precisely.) (不过,如果可能的话,更准确地输入内容会更好。)

我已经使用波纹管表达式解决了这个问题:

let filteredResult = dictionary.filter { !(($0.value as AnyObject) is NSNull) }

if(object_getClass(yourVariable)?.description() == "NSNull")可以是检查的方法之一。

Objective-c property in swift. swift中的Objective-c属性。 If you're using some objective c property in swift and it says something like "Comparing non-optional value of type 'XYZ' to 'nil' always returns true" you have to make that objective c property to "_Nullable" so that property may not be optional anymore.如果您在 swift 中使用了一些目标 c 属性,并且它说“将 'XYZ' 类型的非可选值与 'nil' 进行比较总是返回 true” ,则必须将该目标 c 属性设置为“_Nullable” ,以便该属性可能不再是可选的了。 Like @property (strong,nonatomic) NSString *_Nullable someString;@property (strong,nonatomic) NSString *_Nullable someString;

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

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