Matheus Weber
Matheus Weber

Reputation: 314

AnyObject bool is converted to int

I am creating a Dictionary to hold some values that I will send as parameters in a post request, but when I set a booelan value(true or false) it keeps transforming it to 1 or 0. How can I set to make this true or false instead of 1 or 0?

    var parameters : Dictionary<String, AnyObject> = Dictionary()
    var paramOptions: Dictionary<String, AnyObject> = Dictionary()
    var arrayOptions = [Dictionary<String, AnyObject>]()
    for option in options{
        paramOptions["id"] = option.id
        paramOptions["response"] = option.selected //boolean value
        arrayOptions.append(paramOptions)
    }
    parameters["reason_details"] = Array(arrayOptions)
    Just.post(link, params: parameters) { (r) -> Void in

    }

Upvotes: 0

Views: 1384

Answers (1)

colavitam
colavitam

Reputation: 1322

Update:

The problem actually lies in the type of paramOptions. Bool technically does not conform to AnyObject, and as such, Bool values are converted into numbers to be stored as an AnyObject. Normally, this is not an issue, as they can be freely converted back into Bools.

I don't know the broader scope of this code (or where it has to interoperate with Objective C), but changing your declarations to the following would resolve the issue:

var parameters : Dictionary<String, Any> = Dictionary()
var paramOptions: Dictionary<String, Any> = Dictionary()
var arrayOptions = [Dictionary<String, Any>]()

The issue here is that Bool is not an AnyObject, so the Bool value is being bridged to an NSNumber automatically. Bool is an Any, however, and is left unchanged with the updated types.

Upvotes: 1

Related Questions