How to skip a nil key-value pair in a dictionary mapping

I am using custom code here to map Dictionary

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

      

Mine Dictionary

looks like this:

[String: (TokenView, MediaModel?)]

      

and must be matched against [String : MediaModel]

.

Currently this code:

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

      

displayed on [String : MediaModel?]

.

What should happen is that if it MediaModel

is zero while it is being displayed, that key-value pair should not be appended to the end of the dictionary. How can I change the code for this?

+3


source to share


1 answer


You can use reduce

in a dictionary to get the key / values ​​and create a new dictionary from the values ​​you return from the closure:



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

      

0


source







All Articles