I have an array that looks like this:
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],
]
How would I filter the array to only records with unique types?
Try:
var seenType:[Int:Bool] = [:]
let result = records.filter {
seenType.updateValue(false, forKey: $0["type"] as Int) ?? true
}
Basically this code is a shortcut of the following:
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 of Dictionary returns old value if the key exists, or nil if it's a new key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With