Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the unique id's of objects in an array swift

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 .

like image 383
Anupam Mishra Avatar asked Jul 18 '16 13:07

Anupam Mishra


2 Answers

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)
}
like image 76
Paulw11 Avatar answered Oct 04 '22 04:10

Paulw11


    let uniqueRecords = jobs.reduce([], {
        $0.contains($1) ? $0 : $0 + [$1]
    })
like image 43
Dhaval H. Nena Avatar answered Oct 04 '22 04:10

Dhaval H. Nena