作者:云聪京初瑞子_617 | 来源:互联网 | 2023-05-18 17:41
我有一个看起来像这样的数组:
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],
]
如何将数组过滤为仅包含唯一类型的记录?
1> rintaro..:
尝试:
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
的Dictionary
返回旧值,如果键不存在,或者nil
如果它是一个新的密钥.