[swift-evolution] map-like operation that returns a dictionary

Gwendal Roué gwendal.roue at gmail.com
Wed Jan 13 11:55:26 CST 2016


Doesn’t Swift prefer initializers?

So let’s build a Dictionary initializer that eats any sequence of (key, value) pairs:

extension Dictionary {
    init<S: SequenceType where S.Generator.Element == (Key, Value)>(keyValueSequence s: S) {
        self.init()
        for (key, value) in s {
            self[key] = value
        }
    }
}

do {
    // From array of (key, value) pairs
    let input = [("foo", 1), ("bar", 2)]
    let d = Dictionary(keyValueSequence: input)
    print(d)
}
do {
    // From another dictionary
    let input = [1: "foo", 2: "bar"]
    let d = Dictionary(keyValueSequence: input)
    print(d)
}
do {
    // Reverse key and values
    let input = [1: "foo", 2: "bar"]
    let d = Dictionary(keyValueSequence: input.map { ($1, $0) })
    print(d)
}

Gwendal

> Le 13 janv. 2016 à 18:41, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> I'd prefer "mapToDict" otherwise it sounds like a dictionary gets mapped, at least for me.
> 
> -Thorsten
> 
>> Am 13.01.2016 um 17:13 schrieb Kenny Leung via swift-evolution <swift-evolution at swift.org>:
>> 
>> This solution looks great! How do you feel about “mapDict”?
>> 
>> -Kenny
>> 
>> 
>>>> On Jan 12, 2016, at 10:28 AM, Craig Cruden <ccruden at novafore.com> wrote:
>>>> 
>>>> 
>>>> 
>>>> I named the method(s) „toDict“ instead of „map“ because map normally returns a collection which is either the same as the receiver or a simple one.
>>>> The second version is more general and allows to do things like
>>>> 
>>>> let dict = ["Tom", "Dick", "Harry"].enumerate().toDict { (index, value) in (index + 1, value) }
>>> 
>>> Map would probably be a more correct mathematically speaking — but it would be inconsistent with the naming convention already chosen for Swift.  So for Swift - toDict (or toDictionary) would be the best choice.
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160113/0cce2bf1/attachment.html>


More information about the swift-evolution mailing list