user3766930 user3766930 - 6 months ago 56
Swift Question

why does in Swift3 boolean value from NSUserDefaults is visible as 0 instead of "false"?

In my swift app I'm saving boolean values to


defaults.set(false, forKey: "mySwitch")
defaults.set(true, forKey: "mySecondSwitch")

later on, when I'm constructing query to alamofire:

var params = [
"switch1": defaults.bool(forKey: "mySwitch") as AnyObject
] as [String: AnyObject]

and printing params with
I'm seeing
switch1 = 0
. How can I make it so it's transfered to server as
switch1 = false

I cannot change the structure of the array, it has to stay as
[String: AnyObject]


Whenever you convert a Bool to AnyObject, true becomes 1 and false becomes 0. That behaviour cannot be changed I don't think.

// prints 1
print(true as AnyObject)

The only workaround that I can think of is:

var params = [
    "switch1": defaults.bool(forKey: "mySwitch").description as AnyObject
    ] as [String: AnyObject]

As you can see, I accessed description before as AnyObject. The output is shown below:

["switch1": false]

Apparently, "switch1" gets those quote marks but not false.

Note that I know nothing about Alamofire so I don't know whether sending ["switch1": false] as a parameter to a server will work.