<div dir="ltr"><div>To handle the case of duplicate keys, why not allow to pass in a 'combine' function? This could default to a preconditionFailure to be consistent with the DictionaryLiteral behavior, but be overridden by the caller as needed.<br><br>extension Dictionary {<br> /// Creates a dictionary with the keys and values in the given sequence.<br>
init<S: SequenceType where S.Generator.Element ==
Generator.Element>(_ sequence: S, combine: (existing: Value, other:
Value) -> Value = { preconditionFailure("Sequence contains duplicate
keys"); return $1 } ) {<br> self.init()<br> for (key, value) in sequence {<br> if let existing = updateValue(value, forKey: key) {<br> updateValue(combine(existing: existing, other: value), forKey: key)<br> }<br> }<br> }<br>}<br><br><br></div>usage examples:<br><br><div><br>> A brief draft is below... I had mostly written this up before I saw the thread and Gwendal's similar contribution -- happy to hear feedback and fold in comments/revisions!<br>><br>> Nate<br>><br>><br>> ---<br>><br>><br>> Introduction<br>><br>> The Dictionary type should allow initialization from a sequence of (Key, Value) tuples.<br>><br>> Motivation<br>><br>> Array and Set both have initializers that create a new instance from a sequence of elements. The Array initializer is useful for converting other sequences and collections to the "standard" collection type, but the Set initializer is essential for recovering set operations after performing any functional operations on a set. For example, filtering a set produces a collection without any kind of set operations available:<br>><br>> let numberSet = Set(1 ... 100)<br>> let fivesOnly = numberSet.lazy.filter { $0 % 5 == 0 }<br>><br>> "fivesOnly" is a LazyFilterCollection<Set<Int>> instead of a Set -- sending that back through the Set sequence initializer restores the expected methods:<br>><br>> let fivesOnlySet = Set(numberSet.lazy.filter { $0 % 5 == 0 })<br>> fivesOnlySet.isSubsetOf(numberSet) // true<br>><br>> Dictionary, on the other hand, has no such initializer, so a similar operation leaves no room except for building a mutable Dictionary via iteration or functional methods with dubious performance. These techniques also don't support type inference from the source sequence, increasing verbosity:<br>><br>> var viaIteration: [String: Int] = [:]<br>> for (key, value) in evenOnly {<br>> viaIteration[key] = value<br>> }<br>><br>> let viaFunction: [String: Int] = evenOnly.reduce([:]) { (cumulative, keyValue) in<br>> var mutableDictionary = cumulative<br>> mutableDictionary[keyValue.0] = keyValue.1<br>> return mutableDictionary<br>> }<br>><br>> Proposed solution<br>><br>> The proposed solution would add an initializer to Dictionary that accepts any sequence of (Key, Value) tuple pairs, matching the Dictionary's element type when treated as a sequence:<br>><br>> init<S: SequenceType where S.Generator.Element == Generator.Element>(_ sequence: S)<br>><br>> Instead of the techniques for recovering a Dictionary shown above, the proposed initializer would allow a much cleaner syntax to be written:<br>><br>> let viaProposed = Dictionary(evenOnly)<br>><br>> Moreover, this new initializer would allow for some convenient uses that aren't currently possible.<br>><br>> 👍🏼 Initializing from an array of tuples:<br>><br>> let dictFromArray = Dictionary([("a", 1), ("b", 2), ("c", 3), ("d", 4)])<br>><br>> 👏🏼 Initializing from a DictionaryLiteral (the type, not an actual literal):<br>><br>> let literal: DictionaryLiteral = ["a": 1, "b": 2, "c": 3, "d": 4]<br>> let dictFromDL = Dictionary(literal)<br>><br>> 🎉 Initializing from a pair of zipped sequences (examples abound):<br>><br>> let letters = "abcdefghij".characters.lazy.map { String($0) }<br>> let dictFromZip = Dictionary(zip(letters, 1...10))<br>> // ["b": 2, "a": 1, "i": 9, "j": 10, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, "h": 8]<br>><br>> Potential pitfalls<br>><br>> One caveat is that the new initializer doesn't prevent using a sequence with multiple identical keys. In such a case, the last key/value would "win" and exist in the dictionary. Such an initialization is a compile-time error with a dictionary literal, but succeeds under the new initializer:<br>><br>> let _ = ["z": 1, "z": 2, "z": 3, "z": 4]<br>> // fatal error: Dictionary literal contains duplicate keys<br>> Dictionary([("z", 1), ("z", 2), ("z", 3), ("z", 4)])<br>> // ["z": 4]<br>><br>> This behavior is particularly troublesome when used in conjunction with a mapping operation that modifies a dictionary's keys, since dictionaries have no particular guaranteed order:<br>><br>> let overlapping = Dictionary(dictFromArray.lazy.map { (_, value) in ("z", value) })<br>> // ["z": ???]<br>><br>> While a pitfall, this behavior is less a symptom of the proposed API and more an inherent problem with recovering a dictionary after modifying its keys. The current ways of rebuilding a dictionary (as shown above) are just as susceptible to silently dropping values. Moreover, the sequence-based initializer for Set exhibits the same behavior, though slightly less problematic in most cases:<br>><br>> let dividedNumbers = Set(numberSet.map { $0 / 20 })<br>> // {4, 5, 2, 0, 1, 3}<br>><br>> Given the potential lossiness of the initializer, should it use a parameter name for the sequence? I would suggest not, to match the syntax of Array.init(_:) and Set.init(_:), but a parameter like "collapsingKeys" would make the risk clear to users.<br>><br>> Detailed design<br>><br>> The implementation is simple enough to show in the proposal:<br>><br>> extension Dictionary {<br>> /// Creates a dictionary with the keys and values in the given sequence.<br>> init<S: SequenceType where S.Generator.Element == Generator.Element>(_ sequence: S) {<br>> self.init()<br>> for (key, value) in sequence {<br>> updateValue(value, forKey: key)<br>> }<br>> }<br>> }<br>><br>> (As part of the standard library, this could use the nativeUpdateValue method.)<br>><br>> Impact on existing code<br>><br>> As a new API, this will have no impact on existing code.<br>><br>> Alternatives considered<br>><br>> As suggested in the thread below, a method could be added to SequenceType that would build a dictionary. This approach seems less of a piece with the rest of the standard library, and overly verbose when used with a Dictionary that is only passing through filtering or mapping operations. I don't think the current protocol extension system could handle a passthrough case (i.e., something like "extension SequenceType where Generator.Element == (Key, Value)").<br>><br>> Alternately, the status quo could be maintained. Which would be sad.<br>><br>><br>><br>><br>> > On Jan 13, 2016, at 11:55 AM, Gwendal Roué via swift-evolution <swift-evolution at <a href="http://swift.org">swift.org</a>> wrote:<br>> ><br>> > Doesn’t Swift prefer initializers?<br>> ><br>> > So let’s build a Dictionary initializer that eats any sequence of (key, value) pairs:<br>> ><br>> > extension Dictionary {<br>> > init<S: SequenceType where S.Generator.Element == (Key, Value)>(keyValueSequence s: S) {<br>> > self.init()<br>> > for (key, value) in s {<br>> > self[key] = value<br>> > }<br>> > }<br>> > }<br>> ><br>> > do {<br>> > // From array of (key, value) pairs<br>> > let input = [("foo", 1), ("bar", 2)]<br>> > let d = Dictionary(keyValueSequence: input)<br>> > print(d)<br>> > }<br>> > do {<br>> > // From another dictionary<br>> > let input = [1: "foo", 2: "bar"]<br>> > let d = Dictionary(keyValueSequence: input)<br>> > print(d)<br>> > }<br>> > do {<br>> > // Reverse key and values<br>> > let input = [1: "foo", 2: "bar"]<br>> > let d = Dictionary(keyValueSequence: input.map { ($1, $0) })<br>> > print(d)<br>> > }<br>> ><br>> > Gwendal<br>> ><br>> >> Le 13 janv. 2016 à 18:41, Thorsten Seitz via swift-evolution <swift-evolution at <a href="http://swift.org">swift.org</a> <mailto:<a href="mailto:swift-evolution">swift-evolution</a> at <a href="http://swift.org">swift.org</a>>> a écrit :<br>> >><br>> >> I'd prefer "mapToDict" otherwise it sounds like a dictionary gets mapped, at least for me.<br>> >><br>> >> -Thorsten<br>> >><br>> >>> Am 13.01.2016 um 17:13 schrieb Kenny Leung via swift-evolution <swift-evolution at <a href="http://swift.org">swift.org</a> <mailto:<a href="mailto:swift-evolution">swift-evolution</a> at <a href="http://swift.org">swift.org</a>>>:<br>> >>><br>> >>> This solution looks great! How do you feel about “mapDict”?<br>> >>><br>> >>> -Kenny<br>> >>><br>> >>><br>> >>>>> On Jan 12, 2016, at 10:28 AM, Craig Cruden <ccruden at <a href="http://novafore.com">novafore.com</a> <mailto:<a href="mailto:ccruden">ccruden</a> at <a href="http://novafore.com">novafore.com</a>>> wrote:<br>> >>>>><br>> >>>>><br>> >>>>><br>> >>>>> 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.<br>> >>>>> The second version is more general and allows to do things like<br>> >>>>><br>> >>>>> let dict = ["Tom", "Dick", "Harry"].enumerate().toDict { (index, value) in (index + 1, value) }<br>> >>>><br>> >>>> 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.</div></div>