Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create NSArray of unique key form objects NSArray?

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?

like image 438
edzio27 Avatar asked May 15 '26 01:05

edzio27


2 Answers

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.

like image 109
Antonio Avatar answered May 17 '26 14:05

Antonio


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?]
like image 36
average Joe Avatar answered May 17 '26 15:05

average Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!