[swift-users] Why can I not filter or map a dictionary to another dictionary?

Hooman Mehr hooman at mac.com
Wed Oct 26 23:53:08 CDT 2016


The rational for returning Array is here: https://github.com/apple/swift/blob/master/docs/StdlibRationales.rst#high-order-functions-on-collections-return-arrays <https://github.com/apple/swift/blob/master/docs/StdlibRationales.rst#high-order-functions-on-collections-return-arrays>

I have this simple extension to dictionary:

extension Dictionary {
    
    mutating func append(_ element: Element) {

        self[element.key] = element.value
    }
    
    mutating func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == Element {
        
        for element in sequence { append(element) }
    }
    
    init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element {
        
        self.init()
        self.append(contentsOf: sequence)
    }
}

Which enables doing this:

var d = ["A":1, "B":2, "C": 3, "D": 4, "E": 5]

d.append((key: "F", value: 6))

d.append(contentsOf: ["G": 7, "H": 8])

var e = Dictionary(d.filter { $0.key < "E" })

print(e)

You should note that the meaning of `append` here is different from ordinary (array-like) collections.


> On Oct 26, 2016, at 5:12 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
> 
> It seems fairly natural to want to do this:
> 
> let bigDictionary = ...
> let smallerDictionary = bigDictionary.filter { key, value in <some test returning Bool> }
> 
> Similarly, it seems natural to want to map this way.
> 
> Am I overlooking something?
> 
> -- 
> Rick Mann
> rmann at latencyzero.com
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161026/af078cd8/attachment.html>


More information about the swift-users mailing list