Muli Yulzary Muli Yulzary - 1 year ago 98
iOS Question

Casting custom class to NSDictionary

I've searched everywhere but to no avail:

Can you cast a custom class to NSDictionary?

Use case:

I have a

class containing some properties and I want to save it to Firebase with
taskRef.setValue(task as? NSDictionary())
however I don't even know if this is possible.

Here's my Todo class:

class Todo : NSObject{
var name: String
var desc: String
var date: Double
var location: [Double]?
var snapshot: FIRDataSnapshot?

init(name: String, desc: String? = nil, date: Double, location: [Double]? = nil){ = name
self.desc = desc! = date
self.snapshot = nil
self.location = location

convenience init(name: String, desc: String? = nil, date: NSDate, location: CLLocationCoordinate2D? = nil){
var serLoc: [Double]? = nil
if let location = location {
serLoc = [location.latitude, location.longitude]
self.init(name: name, desc: desc, date: date.timeIntervalSince1970 as Double, location: serLoc)

convenience init(snapshot: FIRDataSnapshot){
let dict = snapshot.value as! [String: AnyObject]
let location = dict["location"] as? [Double]
self.init(name: dict["name"] as! String, desc: dict["desc"] as? String, date: dict["date"] as! Double, location: location)
self.snapshot = snapshot

convenience override init(){
self.init(name: "", desc: "", date: NSDate())


Answer Source

No, you cannot "cast" a custom class to NSDictionary. (Or a Swift dictionary either.) Casting is telling the compiler "Don't worry, this object is really a dictionary. Trust me." Casting is not converting. If you try to CAST a custom object that is not a dictionary to a dictionary, it won't BE a dictionary.

You need to convert your object to a dictionary, not cast it. As Larme suggests in his comment, add a toDictionary method to your class that returns a dictionary that encodes the properties of your object into key/value pairs in the dictionary.

Then create a custom init method that takes a dictionary as a parameter.

I seem to remember reading that there are Swift methods that let you interrogate the properties of an object and get their names. You could write your toDictionary code to use that. If I remember correctly they use Mirror and .children. If you don't want to write custom code to convert your object's properties, take a look at Mirror.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download