I want to create an object from JSON, but if any of the properties aren't set successfully, e.g. the corresponding JSON value is missing or malformed, I want to return a nil object. The upside is that I can then assume that any object created from JSON has all of the required properties, and thus I don't need to use optionals. Is there a way to do this?
Need that, too.
Interesting idea. I will put some thought into how I could add this functionality to the library.
Cheers,
Tristan
@tristanhimmelman Is there an open issue where you're tracking ideas & future developments for official support of non-optional mapping? I understand that it's not possible (or not very elegant) at the moment, but it'd be awesome to gather the current recommended way to do it and brainstorm on other solutions in a single place.
I'm wondering the same thing, @ldiqual. Is there a discussion about pros, cons, and challenges of supporting failable initialization with non-optional model properties. Did you find anything? I'm imagining it must be difficult to do, and there may be some prior discussion of the challenges involved with implementing this.
I tried a few light things, but can't figure a way to do a failable init with non-optional mapping in a symmetrical, DRY way.
This video expresses my critique succinctly--I don't want the transform layer to enforce optional or mutable state in my models:

This is a good option: https://github.com/Hearst-DD/ObjectMapper/pull/216/files
And this was recommended:
required init?(_ map: Map) {
if let id = map["id"].value() {
self.id = id
} else { return nil }
}
...but this won't serialize back out the same way unless I add that to the mapping function, and enforced symmetricality (where foo == Foo(json: foo.toJSON())) is one of the things I love best about this library (along with extendable serializers and the mapping syntax).
Just for further reference regarding this same issue:
The recommended way mentioned in the last comment fails (tested with v2.2.6) with the error Cannot invoke 'value' with no arguments.
value() is generic function and returns a T type inferred from the the variable declaration.
So in order to fix this we should add a type like this (or the type that id belongs to):
required init?(_ map: Map) {
if let id: Int = map["id"].value() {
self.id = id
} else { return nil }
}
Most helpful comment
Just for further reference regarding this same issue:
The recommended way mentioned in the last comment fails (tested with v2.2.6) with the error
Cannot invoke 'value' with no arguments.value()is generic function and returns aTtype inferred from the the variable declaration.So in order to fix this we should add a type like this (or the type that id belongs to):