SpaceX
SpaceX

Reputation: 2890

Boolean value obtained from UserDefaults printing as 0 or 1 even when saved as Any

I am saving a dictionary of type [String : Any] to UserDefaults,

When I print the dictionary before saving to UserDefaults, the boolean value from the dictionary prints as true or false, However when I retrieve the dictionary it prints out as 0 or 1.

I have seen similar SO questions where the advice was to use Any instead of AnyObject which I did.

Below is the code I am using, please advice where I am going wrong.

static var profileDetails : [String: Any]{
    get{
        let defaults        = UserDefaults.standard
        let profileDetailsDict  = defaults.object(forKey: "profileDetails") as? [String: Any] ?? [String : Any]()
        print("Get profileDetailsDict : \(profileDetailsDict), type: \(type(of: profileDetailsDict))")
        return profileDetailsDict
    }
    set (profileDetailsDict){
        let defaults        = UserDefaults.standard

        print("Set profileDetailsDict: \(profileDetailsDict)")
        defaults.set(profileDetailsDict, forKey: "profileDetails")
    }
}


let profileDetailsDict = ["availabilityTimesDict": ["Saturday": ["times": [["startTime": 9:00 AM, "endTime": 1:30 PM], ["startTime": 2:30 PM, "endTime": 6:00 PM]], "weekday": Saturday, "available": true], "Tuesday": ["times": [["startTime": 2:30 PM, "endTime": 6:00 PM]], "weekday": Tuesday, "available": true]], "mobileNumber": "8458465845", "namesArray": ["name1", "name2"]] as [String: Any]


// Setting profileDetailsDict
profileDetails =  profileDetailsDict

// Retrieving profileDetailsDict
let userDetails = profileDetails

Upvotes: 0

Views: 180

Answers (1)

vadian
vadian

Reputation: 285064

That's normal.

When an object is saved to UserDefaults any numeric value is bridged to NSNumber and the representation of true and false in NSNumber is 1 and 0.

You get real true and false back with

dict["available"] as! Bool

Upvotes: 1

Related Questions