[英]How to create NSArray of unique key form objects NSArray?
I have an NSArray of objects: 我有一个NSArray对象:
class Object {
var name: String? = nil
var id: String? = nil
}
I want to create an NSArray of unique 'name' value. 我想创建一个具有唯一“名称”值的NSArray。 Normally in Objective-C I would use:
通常在Objective-C中我会使用:
NSArray *filteredArray = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
but there is no method 'valueForKeyPath' in swift. 但是在swift中没有方法'valueForKeyPath'。 How can I do this in swift?
我怎么能在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). dict
存储已经作为键处理的名称,以及一个布尔值作为值(被忽略)。 I use filter
to produce an array of Object
elements where the name
property is unique, ie discarding all subsequent instances if the name
property is found in the dictionary. 我使用
filter
来生成一个Object
元素数组,其中name
属性是唯一的,即如果在字典中找到name
属性,则丢弃所有后续实例。
Once the array of elements with unique name is obtained, I use map
to transform the array of Object
s into an array of String
, taking the name
property from each Object
instance. 获得具有唯一名称的元素数组后,我使用
map
将Object
的数组转换为String
数组,从每个Object
实例获取name
属性。
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. 如果您要在多个地方重用此方法,最好将其作为扩展方法添加到
Array
类型中。
You can still use the power of NSArray, just make sure your Object
extends NSObject
: 您仍然可以使用NSArray的强大功能,只需确保您的
Object
扩展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?]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.