Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...