Bool being seen as int when using AnyObject

前端 未结 2 1418
南旧
南旧 2020-12-16 21:41

I am using a list of params of type Dictionary in a Swift iOS application to hold some parameters that will eventually be passed to a we

相关标签:
2条回答
  • 2020-12-16 22:29

    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.

    0 讨论(0)
  • 2020-12-16 22:33

    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.

    0 讨论(0)
提交回复
热议问题