Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bool being seen as int when using AnyObject

I am using a list of params of type Dictionary<String,AnyObject> in a Swift iOS application to hold some parameters that will eventually be passed to a webservice. If I were to save a Bool to this dictionary and then print it, it appears as "Optional(1)", so it is being converted to an int. I cannot send an int and need this to be "true". Sample code below.

var params = Dictionary<String,AnyObject>()
params["tester"] = true
println(params["tester"])

How can I get this to save as an actual true/false value and not as an integer?

Caveats

This is being used with AFNetworking, so the parameters are required to be of the form AnyObject!

The AFNetworking structure is as below:

manager.GET(<#URLString: String!#>, parameters: <#AnyObject!#>, success: <#((AFHTTPRequestOperation!, AnyObject!) -> Void)!##(AFHTTPRequestOperation!, AnyObject!) -> Void#>, failure: <#((AFHTTPRequestOperation!, NSError!) -> Void)!##(AFHTTPRequestOperation!, NSError!) -> Void#>)

the 'parameters' argument is what I am passing in the Dictionary<String,AnyObject> as.

like image 930
steventnorris Avatar asked Mar 19 '15 17:03

steventnorris


2 Answers

Instead of:

var params = Dictionary<String,AnyObject>()

Try:

var params = Dictionary<String,Any>()

Any can represent an instance of any type at all, including function types.

Documentation: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-XID_448

In this case it appears you need a Dictionary and the service is expecting "true" as opposed to the bool value.

I recommend creating a function to convert your bool value to a String and using that to set your params["tester"].

Example:

param["tester"] = strFromBool(true)

and then define the function strFromBool to accept a bool parameter and return "true" or "false" depending on its value.

like image 108
chrissukhram Avatar answered Sep 30 '22 00:09

chrissukhram


true really is 1, so it's not inaccurate; it really is storing the Bool, but since it's coming out the other end as AnyObject, it's just printing it out as an integer since it doesn't know the exact type.

You can try to cast it to test for a Bool:

var params = Dictionary<String,AnyObject>()
params["tester"] = true

if let boolValue = params["tester"] as? Bool {
  println("\(boolValue)")
}

That's the safe way to do it.

like image 24
gregheo Avatar answered Sep 29 '22 23:09

gregheo