xcode 快速将任何对象转换为布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39632352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:19:06  来源:igfitidea点击:

Convert any object to boolean in swift?

iosiphoneswiftxcode

提问by TechChain

I am getting a dictionary as JSON response from server.From that dictionary there is a key "error"now i want to get the value of "error" key.I know that error always will be either 0or 1.So i tried to get it as boolean but it did not work for me.Please suggest how can i convert its value to boolean.

我正在从服务器获取一个字典作为 JSON 响应。从那个字典有一个键“错误”,现在我想获得“错误”键的值。我知道错误总是01。所以我试图将其作为布尔值,但它对我不起作用。请建议我如何将其值转换为布尔值。

  let error=jsonResult.objectForKey("error")
  //this does not work for me
   if(!error)
  {
      //proceed ahead
   }

回答by PGDev

Booldoes not contain an initializer that can convert Intto Bool. So, to convert Intinto Bool, you can create an extension, i.e.

Bool不包含可以转换IntBool. 因此,要转换IntBool,您可以创建一个extension,即

extension Bool
{
    init(_ intValue: Int)
    {
        switch intValue
        {
        case 0:
            self.init(false)
        default:
            self.init(true)
        }
    }
}

Now you can get the value of key error using:

现在您可以使用以下方法获取键错误的值:

if let error = jsonResult["error"] as? Int, Bool(error)
{
// error is true
}
else
{
// error does not exist/ false.
}

回答by pdubal

Updated

更新

Considering jsonResult as NSDictionaryand error value is Bool. you can check it by following way.

将 jsonResult 视为NSDictionary,错误值为Bool. 您可以通过以下方式进行检查。

guard let error = jsonResult.object(forKey: "error") as? Bool else{
    // error key does not exist / as boolean
    return
}

if !error {
    // not error
}
else {
    // error
}

回答by Ganpat

Very Simple Way:

很简单的方法:

Create a function:

创建一个函数:

func getBoolFromAny(paramAny: Any)->Bool {
    let str = "\(paramAny)"
    return str == "1"
}

Use the function:

使用函数:

if let anyData = jsonResult["error"] {
    if getBoolFromAny(anyData) {
        // error is true
    } else {
        // error is false
    }
}

Also, if you want one line condition, then above function can be reduced like:

另外,如果你想要一个行条件,那么上面的函数可以减少如下:

if let anyData = jsonResult["error"], getBoolFromAny(anyData) {
    // error is true
} else {
    // error is false
}

回答by gnasher729

Your error is neither 0 or 1. It is an optional object. It is nil if there was no key "error" in your JSON, otherwise it's probably an NSNumber.

您的错误既不是 0 也不是 1。它是一个可选对象。如果您的 JSON 中没有关键的“错误”,则它为零,否则它可能是一个 NSNumber。

It is most likely that nil means "no error" and if it's not nil and contains a zero it means "no error" and if it's not nil and contains a one it means "error" and if it's not nil and contains anything else then something is badly wrong with your json.

很可能 nil 表示“没有错误”,如果它不是 nil 并且包含零,则表示“没有错误”;如果它不是 nil 并且包含一个 1,则表示“错误”,如果它不是 nil 并且包含其他任何内容,则你的 json 有问题。

Try this:

尝试这个:

let errorObject = jsonResult ["error"]
if errorObject == nil or errorObject as? NSInteger == 0 

When I say "try", I mean "try". You're the responsible developer here. Check if it works as wanted with a dictionary containing no error, with a dictionary containing an error 0 or 1, and a dictionary containing for example error = "This is bad".

当我说“尝试”时,我的意思是“尝试”。您是这里的负责开发人员。使用不含错误的字典、包含错误 0 或 1 的字典以及包含例如 error = "This is bad" 的字典检查它是否按需要工作。

回答by TechChain

Below code worked for me

下面的代码对我有用

 if let error = jsonResult["error"] as? Int where Bool(error)
  {
            // error is true
           print("error is true")
  }
  else
  {
      // error does not exist/ false.
      print("error is false")
  }

回答by Gurdeep

Another Important point here is, you're using Swift and parsing the repsonse as NSDictionary. I can say that because you're using objectForKeymethod. Best practice would be to parse it as Swift Dictionary.

这里的另一个重点是,您正在使用 Swift 并将响应解析为 NSDictionary。我可以这么说是因为你在使用objectForKey方法。最佳实践是将其解析为 Swift Dictionary

It may look like Dictionary<String:AnyObject>or [String:AnyObject]

它可能看起来像Dictionary<String:AnyObject>[String:AnyObject]

Then you can check for the error as :

然后你可以检查错误:

  if let error = jsonResult["error"] where error == 0 {
    //your code
  }

回答by Tim Vermeulen

Check equality between errorand 0instead:

检查error和之间的相等性0

let error = jsonResult.objectForKey("error")

if error == 0 {
    // proceed
}