如何在Dictionary映射中跳过nil键值对

时间:2017-07-11 12:39:49

标签: swift

我使用here中的自定义代码将Dictionary映射到Dictionary

extension Dictionary {
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }

    func mapPairs<OutKey: Hashable, OutValue>(_ transform: (Element) throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
        return Dictionary<OutKey, OutValue>(try map(transform))
    }

    func filterPairs(_ includeElement: (Element) throws -> Bool) rethrows -> [Key: Value] {
        return Dictionary(try filter(includeElement))
    }
}

我的Dictionary看起来像这样:

[String: (TokenView, MediaModel?)]

并且需要映射到[String : MediaModel]

目前此代码:

let myDict = strongSelf.tokenViews.mapPairs {($0.key, $0.value.1)}

映射到[String : MediaModel?]

需要发生的是,如果MediaModel在映射时为零,则不应将该键值对添加到结束字典中。如何修改代码以适应这个?

1 个答案:

答案 0 :(得分:0)

您可以在字典上使用reduce来获取键/值,并根据从闭包中获得的值构造新的字典:

func mapPairs<OutKey: Hashable, OutValue>(_ transform: (Element) throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
    return try self.reduce(into: [:]) { result, element in
        let new = try transform(element)
        result[new.0] = new.1
    }
}