3

I am using custom code from here to map a Dictionary to a 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))
    }
}

My Dictionary looks like this:

[String: (TokenView, MediaModel?)]

and needs to be mapped to [String : MediaModel].

Currently this code:

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

maps to [String : MediaModel?].

What needs to happen is that if the MediaModel is nil whilst it's being mapped, that key-value pair should not be added to the end Dictionary. How can I modify the code to accommodate for this?

Paulw11
  • 108,386
  • 14
  • 159
  • 186
Tometoyou
  • 7,792
  • 12
  • 62
  • 108

1 Answers1

1

You could use reduce on the dictionary to get the key/values and construct a new dictionary from the values you get back 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
    }
}
Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92