我有一个如下所示的数组:
let records = [
["created": NSDate(timeIntervalSince1970: 1422600000), "type": 0],
["created": NSDate(timeIntervalSince1970: 1422600000), "type": 0],
["created": NSDate(timeIntervalSince1970: 1422600000), "type": 1],
["created": NSDate(timeIntervalSince1970: 1422600000), "type": 1],
["created": NSDate(timeIntervalSince1970: 1422700000), "type": 2],
["created": NSDate(timeIntervalSince1970: 1422700000), "type": 2],
]
如何将数组过滤为仅包含唯一类型的记录?
答案 0 :(得分:7)
尝试:
var seenType:[Int:Bool] = [:]
let result = records.filter {
seenType.updateValue(false, forKey: $0["type"] as Int) ?? true
}
基本上,此代码是以下内容的快捷方式:
let result = records.filter { element in
let type = element["type"] as Int
// .updateValue(false, forKey:)
let retValue:Bool? = seenType[type]
seenType[type] = false
// ?? true
if retValue != nil {
return retValue!
}
else {
return true
}
}
如果密钥存在,则updateValue
的{{1}}会返回旧值,如果密钥存在,则返回Dictionary
。
答案 1 :(得分:1)
必须有更快捷的方法来做到这一点,但它有效。
var unique = [Int: AnyObject]()
for record in records {
if let type = record["type"] as? Int {
unique[type] = record
}
}