Convert any object to boolean in swift?

10,478

Solution 1

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

Solution 2

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
}

Solution 3

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
}

Solution 4

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

Share:
10,478
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.

Updated on June 18, 2022

Comments

  • TechChain
    TechChain almost 2 years

    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
       }
    
  • Tim Vermeulen
    Tim Vermeulen over 7 years
    You could replace that entire switch by self = intValue == 0 :)
  • gnasher729
    gnasher729 over 7 years
    Who says? The compiler or you?
  • Tim Vermeulen
    Tim Vermeulen over 7 years
    @deepakkumar If it's an integer to begin with, your original code should just work...
  • Peter Suwara
    Peter Suwara almost 5 years
    Thanks, yes that works much better. One thing I found was that in some dictionaries the Bool values comes in as Strings and need a String cast and check against "True".
  • pdubal
    pdubal almost 5 years
    key value depends on how json is built. we can set as string / bool / int.
  • Douglas Frari
    Douglas Frari almost 4 years
    I kept the original answer because the question mentions that the return JSON contains 0 or 1 for that value. However, a more generic function would be an acceptable response: return paramAny as? Bool ?? false