Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift: Filter array to unique items [duplicate]

Tags:

arrays

ios

swift

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?

like image 502
colindunn Avatar asked May 03 '26 03:05

colindunn


1 Answers

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.

like image 172
rintaro Avatar answered May 04 '26 23:05

rintaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!