Kavin Kumar Arumugam
Kavin Kumar Arumugam

Reputation: 1832

iOS Swift Alamofire JSON Response Returning Bool Values as `1` or `0`

In alamofire response I'm returning some Bool Values. But it return as 0 or 1 not true or false. How to make Alamofire JSON response to return it as true or false. Here is my tried code:

Alamofire.request(baseurl, method: .get,encoding: JSONEncoding.default).responseJSON { response in
    let statuscode = response.response?.statusCode
    switch response.result
    {
       case .success(_):
       if ( statuscode == 200)
       {
          let JSON = response.result.value!
          // I'm having some values like `isUserRegistered` is `true` or `false`. But it return as `0` or `1`.
       }
       case .failure(let error):
           print("Request Failed With Error:\(error)")
    }
 }

Upvotes: 2

Views: 2804

Answers (2)

Umair Afzal
Umair Afzal

Reputation: 5039

For Swift 3

You can convert it into bool as followings :

To convert your specfic String values to Bool you can use this extension

extension String {
func toBool() -> Bool? {
    switch self {
    case "True", "true", "yes", "1":
        return true
    case "False", "false", "no", "0":
        return false
    default:
        return nil
    }
}
}

And you can use it as follows

var mySting = "0"
var myBool = myString.toBool()

Upvotes: 0

Developer
Developer

Reputation: 832

You can try a type cast

  let JSON = response.result.value! as Bool

Upvotes: 4

Related Questions