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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With