How can we create unique object list in Swift language like NSSet
& NSMutableSet
in Objective-C.
Always in such a case the critical factor is how to compare objects and what types of objects go into the Set. Using a Swift Dictionary, where the Set objects are the dictionary keys, could be a problem based on the restrictions on the key type (String, Int, Double, Bool, valueless Enumerations or hashable).
If you can define a hash function on your object type then you can use a Dictionary. If the objects are orderable, then you could define a Tree. If the objects are only comparable with ==
then you'll need to iterate over the set elements to detect a preexisting object.
// When T is only Equatable
class Set {
var items = Array()
func hasItem (that: T) {
// No builtin Array method of hasItem...
// because comparison is undefined in builtin Array
for this: T in items {
if (this == that) {
return true
}
}
return false
}
func insert (that: T) {
if (!hasItem (that))
items.append (that)
}
}
The above is an example of building a Swift Set
; the example used objects that are only Equatable
- which, while a common case, doesn't necessarily lead to an efficient Set
implementations (O(N) search complexity - the above is an example).