我有一个看起来像这样的数组:
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],
]
Run Code Online (Sandbox Code Playgroud)
如何将数组过滤为仅包含唯一类型的记录?
尝试:
var seenType:[Int:Bool] = [:]
let result = records.filter {
seenType.updateValue(false, forKey: $0["type"] as Int) ?? true
}
Run Code Online (Sandbox Code Playgroud)
基本上这段代码是以下的快捷方式:
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
}
}
Run Code Online (Sandbox Code Playgroud)
updateValue的Dictionary返回旧值,如果键不存在,或者nil如果它是一个新的密钥.
| 归档时间: |
|
| 查看次数: |
4597 次 |
| 最近记录: |