Bool is treated as int when using AnyObject

I use a list of parameters like Dictionary<String,AnyObject> in a Swift iOS application to store some parameters that will ultimately be passed to the web service. If I were to save the Bool in this dictionary and then print it, it will appear as "Optional (1)", so it will be converted to int. I can not send int and need it to be "true". Sample code below.

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

How can I make this save as the actual true / false value, and not as an integer?

Warnings

This is used with AFNetworking, so the parameters should look like AnyObject!

The AFNetworking structure is as follows:

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

the argument 'parameters' is what I pass to Dictionary<String,AnyObject> as.

+7
dictionary boolean swift
source share
2 answers

Instead:

 var params = Dictionary<String,AnyObject>() 

Try:

 var params = Dictionary<String,Any>() 

Anyone can represent an instance of any type in general, including a function of 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 seems to you that you need a dictionary, and the service expects a "true", not a bool value.

I recommend creating a function to convert your bool value to String and use this to set your parameters ["tester"].

Example:

 param["tester"] = strFromBool(true) 

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

+5
source share

true really 1, so it is not inaccurate; it really stores the Bool, but since it goes to the other end as AnyObject , it just prints it as a whole, because it does not know the exact type.

You can try throwing it to check the Bool:

 var params = Dictionary<String,AnyObject>() params["tester"] = true if let boolValue = params["tester"] as? Bool { println("\(boolValue)") } 

This is a safe way to do it.

+6
source share

All Articles