Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS Swift:将数组筛选为唯一项_Ios_Arrays_Swift - Fatal编程技术网

iOS Swift:将数组筛选为唯一项

iOS Swift:将数组筛选为唯一项,ios,arrays,swift,Ios,Arrays,Swift,我有一个如下所示的数组: let records = [ ["created": NSDate(timeIntervalSince1970: 1422600000), "type": 0], ["created": NSDate(timeIntervalSince1970: 1422600000), "type": 0], ["created": NSDate(timeIntervalSince1970: 1422600000), "type": 1], ["cr

我有一个如下所示的数组:

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],
]
如何将数组筛选为仅具有唯一类型的记录?

尝试:

var seenType:[Int:Bool] = [:]
let result = records.filter {
    seenType.updateValue(false, forKey: $0["type"] as Int) ?? true
}
基本上,此代码是以下内容的快捷方式:

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
    }
}

Dictionary
updateValue
如果键存在,则返回旧值;如果是新键,则返回
nil

必须有一种更快速的方法来实现这一点,但它是有效的

var unique = [Int: AnyObject]()

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

您使用的是哪个版本的Swift?您需要解释答案。为什么这个代码可以工作等等…很好的一个。回答得好,优雅!(即使将
seenType[type]
设置为
false
,如果已经看到了类型,这也是非常违反直觉的:)–使用Swift 1.2,您可能会使用
设置
用于
seenType