8
votes

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.

2
@MartinR The web service isn't the issue at this point, but it is being sent as application/json. the issue is that the AnyObject type converts Bool to an int rather than true/false.steventnorris
I have no experience with AFNetworking, but NSJSONSerialization does handle that correctly.Martin R
@MartinR Your initial thoughts on the webservices seems that it may be the issue. It seems the webservices expects a string true/false, because when it receives a 0/1, which should function fine, it reacts as if it is false every time. If i use the strings "true"/"false", there is no issue.steventnorris

2 Answers

7
votes

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.

6
votes

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.