How to create NSArray objects of unique key form NSArray?
I have NSArray objects:
class Object {
var name: String? = nil
var id: String? = nil
}
I want to create an NSArray with a unique "name" value. Typically in Objective-C I would use:
NSArray *filteredArray = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
but there is no 'valueForKeyPath' method in swift. How can I do this quickly?
source to share
There is no direct way to do this - at least I don't know.
The algorithm to achieve this is to use a dictionary to keep track of unique names and use "filter" and "map":
var dict = [String : Bool]()
let filtered = array.filter { (element: Object) -> Bool in
if let name = element.name {
if dict[name] == nil {
dict[element.name!] = true
return true
}
}
return false
}
let names = filtered.map { $0.name!}
dict
stores names already treated as a key and a boolean as value (which is ignored). I am using filter
to create an array of elements Object
where the property is name
unique i.e. Discards all subsequent instances if the property is name
found in the dictionary.
After getting an array of elements with a unique name, I use map
to convert the array Object
to an array String
using a property name
from each instance Object
.
If you are going to reuse this method in multiple places, it is recommended that you add it as an extension method to the type Array
.
source to share
You can still use the power of NSArray, just make sure your Object
extends NSObject
:
class Object:NSObject {
var name: String? = nil
var id: String? = nil
}
let originalArray = [Object(), Object()]
let array = NSArray(array: originalArray)
let result = array.valueForKeyPath("@distinctUnionOfObjects.name") as [String?]
source to share