3

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?

colindunn
  • 3,139
  • 10
  • 48
  • 72

2 Answers2

7

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.

rintaro
  • 51,423
  • 14
  • 131
  • 139
1

There has got to be a more swift way to do this but it works.

var unique = [Int: AnyObject]()

for record in records {
    if let type = record["type"] as? Int {
        unique[type] = record
    }
}

enter image description here

Price Ringo
  • 3,424
  • 1
  • 19
  • 33