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?

1
  • Which version of Swift you are using? Commented Mar 10, 2015 at 7:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You need to explain the answer. Why does this code work etc...
nice one. Good answer.
Elegant! (Even if setting seenType[type] to false if the type has been seen is quite counter-intuitive :) – With Swift 1.2 one could probably use a Set for seenType.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.