5

I have a custom class like this -

class Event: NSObject
{
    var eventID: String?
    var name:String?
}

Now i have an array of Event object's like

var events = [Event]()

var event1 = Event()
event1.eventID = "1"
event1.name = "Anu"

var event2 = Event()
event2.eventID = "2"
event2.name = "dev"

var event3 = Event()
event3.eventID = "1"
event3.name = "Anu"

events.append(event1)
events.append(event2)
events.append(event3)

to get the unque eventID's from array i have written code like this which is working great -

func getUniqueIDsFromArrayOfObjects(events:[Event])->NSArray
{
    let arr = events.map { $0.eventID!}
    let uniquearr:NSMutableArray = NSMutableArray()
    for obj in arr
    {
        if !uniquearr.containsObject(obj) {
            uniquearr.addObject(obj)
        }
    }
    return uniquearr;
}

print(getUniqueIDsFromArrayOfObjects(events))

I wanted to know is there any alternate way to get the unique id's from array of objects more effectively than i am using . May be something by using NSPredicate.

Because an array having thousands of objects, my code going to do more iteration .

Anupam Mishra
  • 3,408
  • 5
  • 35
  • 63
  • 1
    Simplest way i would suggest is to create a Set. – Vivek Molkar Jul 18 '16 at 13:08
  • If you do not care about the order of the resulting array then you can simply use: let finalArray = Array(Set(arr)) – Mohammed Shakeer Jul 18 '16 at 13:27
  • Possible duplicate of [Does there exist within Swift's API an easy way to remove duplicate elements from an array?](http://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro) – dfrib Jul 18 '16 at 13:28

3 Answers3

10

You can use a Set to obtain only the unique values. I would suggest that you have your function return a Swift array rather than NSArray too.

func getUniqueIDsFromArrayOfObjects(events:[Event])->[String]
{
   let eventIds = events.map { $0.eventID!}
   let idset = Set(eventIds)
   return Array(idset)
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
1
    let uniqueRecords = jobs.reduce([], {
        $0.contains($1) ? $0 : $0 + [$1]
    })
Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50
0

A Set is a collection similar to an array, which prevents duplicates. You can do:

func getUniqueIDsFromArrayOfObjects(events:[Event])->[Event] {
    return Array(Set(events.map { $0.eventID! }))
}

Note that the order of the items in a set is undefined, so if you care about the order of the elements, you should try a different solution.

Connor Neville
  • 7,291
  • 4
  • 28
  • 44