initWithDictionary: in Objective-C and Swift

1.9k Views Asked by At

In Objective-C we can use object mapping with json response like this way

 PolicyData *policyData = [[PolicyData alloc] initWithDictionary:responseObject error:&err];

Here we can map responseObject with PolicyData class properties. How i can do the same in Swift?

2

There are 2 best solutions below

3
On BEST ANSWER

It should be as easy as adding a bridging header (because PolicyData is likely written in Objective-C). Instructions on how to do this can be seen in this Apple documentation.

Then you can create that PolicyData object as easily as doing:

do {
    let newPolicyDataObject = try PolicyData(responseObject)
} catch error as NSError {
    print("error from PolicyData object - \(error.localizedDescription)")
}

This assumes your responseObject is a NSDictionary. And Swift 2 helpfully (?) turns error parameters into try/catch blocks.

That is, PolicyData's

- (instancetype) initWithDictionary:(NSDictionary *)responseObject error:(NSError *)err;

declaration magically becomes

func initWithDictionary(responseObject : NSDictionary) throws

as described in the "Error Handling" section of this Apple Objective-C/Swift interoperability doc.

3
On

You can add a

convenience init?(dictionary: NSDictionary)

to any object you want to initialize from a dictionary and initialize it's properties there.

Yet, as swift does no dynamic dispatching (sooner or later), you may not generalize that to expect the properties' names to be keys in the dictionary for any object.