1

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?

Sofeda
  • 1,361
  • 1
  • 13
  • 23

2 Answers2

2

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.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • The `init` method is most likely turned into `PolicyData(dictionary:responseObject)` – vadian Feb 28 '16 at 11:12
  • What if i create PolicyData in swift? In func initWithDictionary(responseObject : NSDictionary) throws , do i have to map all the dictionary keys hardcoded? which i don't want to. – Sofeda Feb 28 '16 at 11:54
  • I don't know what the code inside your PolicyData `init` method looks like... if you're using AFNetworking, [other people have tried the approach](http://stripysock.com.au/blog/2014/7/11/fetching-and-parsing-json-with-swift) you are thinking of and you might have luck digging around on [so]. – Michael Dautermann Feb 28 '16 at 12:15
2

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.

Tobi Nary
  • 4,566
  • 4
  • 30
  • 50
  • Can you please explain why Swift has no dynamic dispatching? Will it give Swift any advantage over Objective-C? – Sofeda Feb 28 '16 at 11:57
  • 1
    Dynamic dispatch can break swifts safety; with dynamic dispatch, there may be implementations switched at runtime that do not adhere to compiler-enforced rules. – Tobi Nary Feb 28 '16 at 12:21
  • Thanks a lot Jan. Any reference for details understanding? – Sofeda Feb 28 '16 at 12:32