-
Notifications
You must be signed in to change notification settings - Fork 73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Inverse relationship mapping #53
Comments
class A: Decodable {
var array: [B] = []
required init(json: AnyObject) throws {
self.array = try decodeArray(B.decode(a: self))(json: json)
}
static func decode(json: AnyObject) throws -> Self {
return try self.init(json: json)
}
}
class B {
weak var a: A?
let name: String
required init(name: String) {
self.name = name
}
static func decode(a a: A)(json: AnyObject) throws -> Self {
let b = try self.init(name: String.decode(json))
b.a = a
return b
}
}
let array: NSArray = ["San Fransisco", "Sparks", "Snow"]
let a = try A.decode(array)
a === a.array[1].a |
What if it's not an array and just a Can't we have an overloaded version of
that takes an |
How do you mean? |
Oh, sorry, was confused by the latter part. You perhaps figured it out by now, but with one-to-one relationships we can just write a custom decode or init function for But in the (curried) example above it would be: // Instead of: self.array = try decodeArray(B.decode(a: self))(json: json)
self.b = try B.decode(a: self)(json: json) And without currying, perhaps this order would be nicer: self.b = try B.decode(json, a: self) |
How would you map an inverse relationship using decodable?
Think of the following scenario:
A <-->> B
With
A
being in ato-many
relationship withB
andB
being in ato-one
relationship withA
.When trying to decode
A
(assuming an array ofB
objects are contained in the payload), the decoding ofB
will be triggered as well.I can't think of a way using decodable for populating the
B
'sA
reference (inverse relationship).In theory all will be needed is to pass
Self
(A
) to the mapping ofB
(in thedecode
function is the only thing I can think of), then havingB
recognise that object, maybe asroot
orparent
and assign it to theA
's reference it holds.The text was updated successfully, but these errors were encountered: