1

I have the list of following model class

struct CommonRes {
var month: String?
var monthName: String?
var year: String?
var classIdCount: String?
var groupName: String?
}
 var res = [CommonRes]()

In the response I am receiving the duplicate values of monthName. I want to make the list of these common monthName by removing duplicates. So from this I have tried the following

 self.monthList = Array(Set(res.filter({ (i : CommonRes) in res.filter({ $0.monthName == i.monthName }).count > 1 })))

But I am receiving an error

Ambiguous reference to member 'filter'

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
Kiran S Kulkarni
  • 215
  • 1
  • 2
  • 16

1 Answers1

2

You can try this.

let monthList = Set(res.compactMap( {$0.monthName} )).sorted()

If you want to preserve the order of your data source then you can use NSOrderedSet.

let monthListOrdered = NSOrderedSet(array: res.compactMap( {$0.monthName})).array as! [String]

However if you want the months in the order they appear on the calender, you need to sort them as dates.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"
let monthList = Set(res.compactMap( {$0.monthName}))
let sortedMonthList = monthList.sorted(by: { dateFormatter.date(from: $0)! < dateFormatter.date(from: $1)! })

Important Note: Force-unwrapping has been done because it is obvious from the data source that you will receive only valid months.

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50