I have an NSArray of objects:
class Object {
var name: String? = nil
var id: String? = nil
}
I want to create an NSArray of unique 'name' value. Normally in Objective-C I would use:
NSArray *filteredArray = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
but there is no method 'valueForKeyPath' in swift. How can I do this in swift?
There's no direct way to do that - at least, I don't know any.
An algorithm to achieve that is to use a dictionary to keep track of unique names, and taking advantage of '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 processed as key, and a boolean as value (which is ignored).
I use filter to produce an array of Object elements where the name property is unique, i.e. discarding all subsequent instances if the name property is found in the dictionary.
Once the array of elements with unique name is obtained, I use map to transform the array of Objects into an array of String, taking the name property from each Object instance.
If you're going to reuse this method in several places, it's a good idea to add it as an extension method to the Array type.
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?]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With