I want to sort an Array of objects, by the properties it shares with another Array of objects
struct GeneralComposition : Decodable {
let id, formId, relationId, fixedContentTypeId, separatorId: Int
let orderBy: Int
}
struct FixedContentType: Decodable {
let name, htmlType: String
let isEditable: Int
let typeId : String
}
var fixedContentType = [FixedContentType]()
var generalComposition = [GeneralComposition]()
In GeneralComposition
I get the order the items must have, with orderBy
, and then take every item's fixedContentTypeID
, compare with the typeId
in FixedContentType
to get the order in which this content must be showed in screen.
Any idea about how can it be done?
Thanks!
1 Answer 1
You can build a dictionary for the fixedContentTypeID
’s of generalComposition
:
let order = generalComposition.reduce(into: [Int: Int]()) { result, value in
result[value.fixedContentTypeId] = value.orderBy
}
You now have an efficient way to lookup the orderBy
value for a given typeId
within your array of FixedContentType
objects. You can use that for sorting:
fixedContentType.sort {
(order[0ドル.typeId] ?? 0) < (order[1ドル.typeId] ?? 0)
}
By the way, your typeId
is a String
, and fixedContentTypeId
is an Int
. I’m assumed that was a typo introduced when preparing the question, and that they’re really both Int
. If they’re really different types (which would be weird), the solution would be similar, though you’d have to do some conversions. But I didn’t want to go there unless you confirmed that this is really what you model was.
But, given that your typeId
really is a String
, you could make your dictionary a [String: Int]
:
let order = generalComposition.reduce(into: [String: Int]()) { result, value in
result[String(value.fixedContentTypeId)] = value.orderBy
}
-
What about a protocol ?Mohmmad S– Mohmmad S2019年03月16日 00:46:17 +00:00Commented Mar 16, 2019 at 0:46
-
make protocol that have the shared properties and an array of this protocol and sort that ?Mohmmad S– Mohmmad S2019年03月16日 01:02:51 +00:00Commented Mar 16, 2019 at 1:02
-
2I’d suggest you post you own answer showing how you’d propose using a protocol. I personally don’t see how that would help. The main thrust of my answer is using a dictionary to achieve O(1) performance for the retrieval of the
orderBy
values.Rob– Rob2019年03月16日 01:06:13 +00:00Commented Mar 16, 2019 at 1:06 -
1if i wanted to answer i would've i want to know the difference and gain exp from the high tier ^_^ thanks anywayMohmmad S– Mohmmad S2019年03月16日 01:07:07 +00:00Commented Mar 16, 2019 at 1:07
-
1one day i will care about the O(1), just like you do sir.Mohmmad S– Mohmmad S2019年03月16日 01:28:26 +00:00Commented Mar 16, 2019 at 1:28
indexOf
pattern is not applicable here.index(of:)
the identifier in the second array, but rather a property of the objects in that second array, like this one. I looked and one didn’t jump out at me, but I bet there’s one out there...