简体   繁体   English

Swift:测试非可选值是否为零/未设置

[英]Swift: test if a non-optional value is nil / not set

I have the following line of code:我有以下代码行:

var info = [String : Any]()

Later i need to compare if info is not nil / set:稍后我需要比较info是否不为零/设置:

Something like this:像这样的东西:

        if(info != nil){
            InfoCenter.default().info = info
        }

But XCode warns: Comparing non-optional value of type '[String : Any]' to nil always returns true但 XCode 警告: Comparing non-optional value of type '[String : Any]' to nil always returns true

How can I fix this?我怎样才能解决这个问题?

Thanks for any help.谢谢你的帮助。

You can check if the Dictionary is empty.您可以检查字典是否为空。

if !info.isEmpty {
    InfoCenter.default().info = info
}

If you're expecting info to be nil , you must declare it as an optional Dictionary like,如果您希望infonil ,则必须将其声明为optional Dictionary例如,

var info: [String:Any]?

Now, use if-let to get the value of info and check the elements in it using isEmpty , ie现在,使用if-let获取info的值并使用isEmpty检查其中的元素,即

if let info = info, !info.isEmpty {
    InfoCenter.default().info = info
}

By using following通过使用以下

var info = [String : Any]()

Means you have initialized info object, Which means its not nil it have a empty value.意味着你已经初始化了 info 对象,这意味着它不是 nil 它有一个空值。 So swift compiler trying to tell you that info object will never be nil according to above declaration.所以 swift 编译器试图告诉你,根据上面的声明, info 对象永远不会为零。 To remove this warning you can do use optional binding.要删除此警告,您可以使用可选绑定。

var info :[String : Any]?
**OR**
var info :[String : Any]!

Try this尝试这个

if info.count != 0
{
    InfoCenter.default().info = info            
}

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

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