Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert any object to boolean in swift?

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 0 or 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.

  let error=jsonResult.objectForKey("error")
  //this does not work for me
   if(!error)
  {
      //proceed ahead
   }
like image 691
TechChain Avatar asked Sep 22 '16 07:09

TechChain


4 Answers

Bool does not contain an initializer that can convert Int to Bool. So, to convert Int into Bool, you can create an extension, i.e.

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.
}
like image 52
PGDev Avatar answered Oct 10 '22 00:10

PGDev


Updated

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

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

if !error {
    // not error
}
else {
    // error
}
like image 45
pdubal Avatar answered Oct 10 '22 01:10

pdubal


Very Simple Way: [Updated Swift 5]

Create a function:

func getBoolFromAny(paramAny: Any)->Bool {
    let result = "\(paramAny)"
    return result == "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
}
like image 27
Ganpat Avatar answered Oct 10 '22 01:10

Ganpat


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.

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.

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".

like image 40
gnasher729 Avatar answered Oct 10 '22 01:10

gnasher729