This is my code:
class Birthgiver {}
class Son: Birthgiver {}
class Daughter: Birthgiver {}
class BirthgiverHolder {
let sons: [Son]
let daughters: [Daughter]
init(birthGivers: [Birthgiver]) {
// How to initializer both sons and daugthers in 1 loop?
// This is my current way (looping twice):
sons = birthGivers.compactMap { $0 as? Son }
daughters = birthGivers.compactMap { $0 as? Daughter }
}
}
I am looping twice over the array birthGivers. Is there some way I can initialize both sons and daughters while only looping once over birthGivers? I don't want to mark the arrays as vars.
birthGivershas 100s of objects, I wouldn't worry about it. The trivial overhead of looping twice outweighs the more difficult to read code you would need to write to loop once.Birthgiver, so in my case it could benefit a lot (without profiling it, but I am still wondering if there is an answer)