How to create array of unique object list in Swift
As of Swift 1.2 (Xcode 6.3 beta), Swift has a native set type.
From the release notes:
A new
Set
data structure is included which provides a generic
collection of unique elements, with full value semantics. It bridges
withNSSet
, providing functionality analogous toArray
andDictionary
.
Here are some simple usage examples:
// Create set from array literal:
var set = Set([1, 2, 3, 2, 1])
// Add single elements:
set.insert(4)
set.insert(3)
// Add multiple elements:
set.unionInPlace([ 4, 5, 6 ])
// Swift 3: set.formUnion([ 4, 5, 6 ])
// Remove single element:
set.remove(2)
// Remove multiple elements:
set.subtractInPlace([ 6, 7 ])
// Swift 3: set.subtract([ 6, 7 ])
print(set) // [5, 3, 1, 4]
// Test membership:
if set.contains(5) {
print("yes")
}
but there are far more methods available.
Update: Sets are now also documented in the "Collection Types" chapter of the Swift documentation.
Unique array of objects
You need to add this extension to return an ordered set from your people array.
extension Collection where Element: Hashable {
var orderedSet: [Element] {
var set: Set<Element> = []
return reduce(into: []){ set.insert($1).inserted ? $0.append($1) : () }
}
}
You will also have to make your Person class Equatable:
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.id == rhs.id
}
class Person: Equatable {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
}
Testing
let person1 = Person(id: "1", name: "Adam")
let person2 = Person(id: "1", name: "Adam")
let person3 = Person(id: "2", name: "John")
let person4 = Person(id: "2", name: "John")
let person5 = Person(id: "3", name: "Michael")
let person6 = Person(id: "4", name: "Nick")
let person7 = Person(id: "5", name: "Tony")
let people = [person1,person2,person3,person4,person5,person6,person7]
people.orderedSet //[{id "1", name "Adam"}, {id "2", name "John"}, {id "3", name "Michael"}, {id "4", name "Nick"}, {id "5", name "Tony"}]
Unique Objects inside a Array Swift
You can use Swift Set
:
let array = [product,product2,product3]
let set = Set(array)
You have to make Product
conform to Hashable
(and thus, Equatable
) though:
class Product : Hashable {
var subCategory = ""
var hashValue: Int { return subCategory.hashValue }
}
func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.subCategory == rhs.subCategory
}
And, if Product
was a NSObject
subclass, you have to override isEqual
:
override func isEqual(object: AnyObject?) -> Bool {
if let product = object as? Product {
return product == self
} else {
return false
}
}
Clearly, modify those to reflect other properties you might have in your class. For example:
class Product : Hashable {
var category = ""
var subCategory = ""
var hashValue: Int { return [category, subCategory].hashValue }
}
func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.category == rhs.category && lhs.subCategory == rhs.subCategory
}
get distinct elements in an array by object property
Hope this will help you:
class Item:Equatable, Hashable {
var name: String
init(name: String) {
self.name = name
}
var hashValue: Int{
return name.hashValue
}
}
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name
}
let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]
var uniqueArray = Array(Set(items))
getting unique items in an array
let uniqueList = nationalities.reduce([], {
$0.contains($1) ? $0 : $0 + [$1]
})
How can I get array object of unique value using Higher Order Functions of swift
A solution with Dictionary(grouping:by:)
let array = [1, 2, 3, 1, 3, 4, 2, 1]
let output = Dictionary(grouping: array, by: {$0})
.values
.sorted(by: { $0[0] < $1[0] })
How to get the unique id's of objects in an array swift
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)
}
Related Topics
Photopicker Discovery Error: Error Domain=Pluginkit Code=13
How to Apply the Type to a Nsfetchrequest Instance
Getting Keyboard Size from Userinfo in Swift
Instance Member Cannot Be Used on Type
Main Thread Checker: Ui API Called on a Background Thread: -[Uiapplication Applicationstate]
First Item in a List Is Always Selected
Swift Beta 6 - Confusing Linker Error Message
How to Import a Swift File from Another Swift File
How to Copy End of the Array in Swift
Multiple Sheet(Ispresented:) Doesn't Work in Swiftui
How to Create Local Scopes in Swift
How to Create Generic Protocols in Swift
How to Reset the App Between Tests in Swift Xctest Ui