Swift Userdefaults converting String to __NSCFString

234 views Asked by At

I have code that save a dictionary of [String: Any] in UserDefaults. On retrieval String are changed to __NSCFString. I am using Mixpanel to track events and sends this dictionary as events properties. Now the problem is __NSCFString is not a valid MixpanelType so Mixpanel is discarding my dictionary.

Questions:

  • Is there a way to get same datatypes that are saved using dictionary in UserDefaults?
  • Is there a way Mixpanel accepts converted datatypes?

Here is a code I am using

var mixpanelProperties: [String: Any] {
    get { defaults.dictionary(forKey: "\(#function)") ?? [:] }
    set { defaults.set(newValue, forKey: "\(#function)") }
}

mixpanelProperties = ["a-key": "value for the key"]
let prop = mixpanelProperties
print("Type of: \(String(describing: prop["a-key"]))")

asdad

1

There are 1 answers

0
gnasher729 On

MacOS and iOS use a variety of different classes to represent strings, which are all compatible. x as? String should just work, no matter what the concrete class of x is. Unless you use code that explicitely checks the class which you shouldn't do.