iOS- swift 3- Nested sorting and union with flatmap, map, filter or formUnion

429 views Asked by At
class Flight{
    var name:String?
    var vocabulary:Vocabulary?
}


class Vocabulary{
    var seatMapPlan:[Plan] = []
    var foodPlan:[Plan] = []
}

class Plan{
    var planName:String?
    var planId:String?
}


var flightList:[Flight] = []
var plan1 = Plan()
plan1.planId = "planId1"
plan1.planName = "Planname1"

var plan2 = Plan()
plan2.planId = "planId2"
plan2.planName = "Planname2"

var plan3 = Plan()
plan3.planId = "planId3"
plan3.planName = "Planname3"

var plan4 = Plan()
plan4.planId = "planId4"
plan4.planName = "Planname4"

var plan5 = Plan()
plan5.planId = "planId5"
plan5.planName = "Planname5"

var plan6 = Plan()
plan6.planId = "planId6"
plan6.planName = "Planname6"

var flight1 = Flight()
flight1.name = "Flight1"
flight1.vocabulary = Vocabulary()
flight1.vocabulary?.seatMapPlan = [plan1, plan2]
flight1.vocabulary?.foodPlan = [plan3, plan4, plan5]


var flight2 = Flight()
flight2.name = "Flight2"
flight2.vocabulary = Vocabulary()
flight2.vocabulary?.seatMapPlan = [plan2, plan3]
flight2.vocabulary?.foodPlan = [plan3, plan4, plan5]

flightList=[flight1, flight2]

Problem 1: I want to use flatmap,filter,custom unique func or Sets.formUnion to achieve a union of seatMapPlans. For this particular example it is

seatMapUnion = [plan1,plan2,plan3]

Because of nesting with the help of answered questions I am unable to achieve this. Please give me a combination of filter,flatMap and map for resolving this particular problem.

Problem 2: I have vice-versa scenarios too were i have to sort this array flightList on basis of plan(plan1 or multiple) selected. I want to sort this on basis of filter and map, but the nesting is making it difficult to achieve. e.g. 1: if the search parameter is plan1 for seatMapPlan. Then the result is flight1.

e.g. 2: And if the search parameter is plan2 for seatMapPlan. Then the result is flight1,flight2.

1

There are 1 answers

1
Bogdan Farca On

For the first problem I would use sets. So first make Plan implement Hashable :

class Plan : Hashable {
    var planName:String?
    var planId:String?

    public var hashValue: Int { return planName?.hashValue ?? 0 }
    public static func ==(lhs: Plan, rhs: Plan) -> Bool { return lhs.planId == rhs.planId }
}

Then it's straightforward :

let set1 = Set<Plan>(flight1.vocabulary!.seatMapPlan)
let set2 = Set<Plan>(flight2.vocabulary!.seatMapPlan)

let union = set1.union(set2)
print(union.map { $0.planName! } )

It'll print:

["Planname2", "Planname1", "Planname3"]

Not sure I understand your second problem.