Anupam Mishra Anupam Mishra -4 years ago 76
Swift Question

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
object's like

var events = [Event]()

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

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

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


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 = { $0.eventID!}
let uniquearr:NSMutableArray = NSMutableArray()
for obj in arr
if !uniquearr.containsObject(obj) {
return uniquearr;


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

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

Answer Source

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 = { $0.eventID!}
   let idset = Set(eventIds)
   return Array(idset)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download