iOS版雨燕:滤镜阵列,以独特的项目 [英] iOS Swift: Filter array to unique items

查看:168
本文介绍了iOS版雨燕:滤镜阵列,以独特的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,看起来像这样:

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?

推荐答案

尝试:

var seenType:[Int:Bool] = [:]
let result = records.filter {
    seenType.updateValue(false, forKey: $0["type"] as Int) ?? true
}

这基本上code是下面的快捷方式:

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 词典返回旧值的如果该键不存在,或者,如果它是一个新的密钥。

updateValue of Dictionary returns old value if the key exists, or nil if it's a new key.

这篇关于iOS版雨燕:滤镜阵列,以独特的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆