forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDictionary.swift
2156 lines (2017 loc) · 74 KB
/
Dictionary.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Implementation notes
// ====================
//
// `Dictionary` uses two storage schemes: native storage and Cocoa storage.
//
// Native storage is a hash table with open addressing and linear probing. The
// bucket array forms a logical ring (e.g., a chain can wrap around the end of
// buckets array to the beginning of it).
//
// The logical bucket array is implemented as three arrays: Key, Value, and a
// bitmap that marks valid entries. An unoccupied entry marks the end of a
// chain. There is always at least one unoccupied entry among the
// buckets. `Dictionary` does not use tombstones.
//
// In addition to the native storage, `Dictionary` can also wrap an
// `NSDictionary` in order to allow bridging `NSDictionary` to `Dictionary` in
// `O(1)`.
//
// Native dictionary storage uses a data structure like this::
//
// struct Dictionary<K,V>
// +------------------------------------------------+
// | enum Dictionary<K,V>._Variant |
// | +--------------------------------------------+ |
// | | [struct _NativeDictionary<K,V> | |
// | +---|----------------------------------------+ |
// +----/-------------------------------------------+
// /
// |
// V
// class __RawDictionaryStorage
// +-----------------------------------------------------------+
// | <isa> |
// | <refcount> |
// | _count |
// | _capacity |
// | _scale |
// | _age |
// | _seed |
// | _rawKeys |
// | _rawValue |
// | [inline bitset of occupied entries] |
// | [inline array of keys] |
// | [inline array of values] |
// +-----------------------------------------------------------+
//
// Cocoa storage uses a data structure like this:
//
// struct Dictionary<K,V>
// +----------------------------------------------+
// | enum Dictionary<K,V>._Variant |
// | +----------------------------------------+ |
// | | [ struct __CocoaDictionary | |
// | +---|------------------------------------+ |
// +----/-----------------------------------------+
// /
// |
// V
// class NSDictionary
// +--------------+
// | [refcount#1] |
// | etc. |
// +--------------+
// ^
// |
// \ struct __CocoaDictionary.Index
// +--|------------------------------------+
// | * base: __CocoaDictionary |
// | allKeys: array of all keys |
// | currentKeyIndex: index into allKeys |
// +---------------------------------------+
//
//
// The Native Kinds of Storage
// ---------------------------
//
// The native backing store is represented by three different classes:
// * `__RawDictionaryStorage`
// * `__EmptyDictionarySingleton` (extends Raw)
// * `_DictionaryStorage<K: Hashable, V>` (extends Raw)
//
// (Hereafter `Raw`, `Empty`, and `Storage`, respectively)
//
// In a less optimized implementation, `Raw` and `Empty` could be eliminated, as
// they exist only to provide special-case behaviors.
//
// `Empty` is the a type-punned empty singleton storage. Its single instance is
// created by the runtime during process startup. Because we use the same
// instance for all empty dictionaries, it cannot declare type parameters.
//
// `Storage` provides backing storage for regular native dictionaries. All
// non-empty native dictionaries use an instance of `Storage` to store their
// elements. `Storage` is a generic class with a nontrivial deinit.
//
// `Raw` is the base class for both `Empty` and `Storage`. It defines a full set
// of ivars to access dictionary contents. Like `Empty`, `Raw` is also
// non-generic; the base addresses it stores are represented by untyped raw
// pointers. The only reason `Raw` exists is to allow `_NativeDictionary` to
// treat `Empty` and `Storage` in a unified way.
//
// Storage classes don't contain much logic; `Raw` in particular is just a
// collection of ivars. `Storage` provides allocation/deinitialization logic,
// while `Empty`/`Storage` implement NSDictionary methods. All other operations
// are actually implemented by the `_NativeDictionary` and `_HashTable` structs.
//
// The `_HashTable` struct provides low-level hash table metadata operations.
// (Lookups, iteration, insertion, removal.) It owns and maintains the
// tail-allocated bitmap.
//
// `_NativeDictionary` implements the actual Dictionary operations. It
// consists of a reference to a `Raw` instance, to allow for the possibility of
// the empty singleton.
//
//
// Index Invalidation
// ------------------
//
// FIXME: decide if this guarantee is worth making, as it restricts
// collision resolution to first-come-first-serve. The most obvious alternative
// would be robin hood hashing. The Rust code base is the best
// resource on a *practical* implementation of robin hood hashing I know of:
// https://github.com/rust-lang/rust/blob/ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0/src/libstd/collections/hash/map.rs#L70-L178
//
// Indexing a container, `c[i]`, uses the integral offset stored in the index
// to access the elements referenced by the container. Generally, an index into
// one container has no meaning for another. However copy-on-write currently
// preserves indices under insertion, as long as reallocation doesn't occur:
//
// var (i, found) = d.find(k) // i is associated with d's storage
// if found {
// var e = d // now d is sharing its data with e
// e[newKey] = newValue // e now has a unique copy of the data
// return e[i] // use i to access e
// }
//
// The result should be a set of iterator invalidation rules familiar to anyone
// familiar with the C++ standard library. Note that because all accesses to a
// dictionary storage are bounds-checked, this scheme never compromises memory
// safety.
//
// As a safeguard against using invalid indices, Set and Dictionary maintain a
// mutation counter in their storage header (`_age`). This counter gets bumped
// every time an element is removed and whenever the contents are
// rehashed. Native indices include a copy of this counter so that index
// validation can verify it matches with current storage. This can't catch all
// misuse, because counters may match by accident; but it does make indexing a
// lot more reliable.
//
// Bridging
// ========
//
// Bridging `NSDictionary` to `Dictionary`
// ---------------------------------------
//
// FIXME(eager-bridging): rewrite this based on modern constraints.
//
// `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`,
// without memory allocation.
//
// Bridging to `Dictionary<AnyHashable, AnyObject>` takes `O(n)` time, as the
// keys need to be fully rehashed after conversion to `AnyHashable`.
//
// Bridging `NSDictionary` to `Dictionary<Key, Value>` is O(1) if both Key and
// Value are bridged verbatim.
//
// Bridging `Dictionary` to `NSDictionary`
// ---------------------------------------
//
// `Dictionary<K, V>` bridges to `NSDictionary` in O(1)
// but may incur an allocation depending on the following conditions:
//
// * If the Dictionary is freshly allocated without any elements, then it
// contains the empty singleton Storage which is returned as a toll-free
// implementation of `NSDictionary`.
//
// * If both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` is
// still toll-free bridged to `NSDictionary` by returning its Storage.
//
// * If the Dictionary is actually a lazily bridged NSDictionary, then that
// NSDictionary is returned.
//
// * Otherwise, bridging the `Dictionary` is done by wrapping it in a
// `_SwiftDeferredNSDictionary<K, V>`. This incurs an O(1)-sized allocation.
//
// Complete bridging of the native Storage's elements to another Storage
// is performed on first access. This is O(n) work, but is hopefully amortized
// by future accesses.
//
// This design ensures that:
// - Every time keys or values are accessed on the bridged `NSDictionary`,
// new objects are not created.
// - Accessing the same element (key or value) multiple times will return
// the same pointer.
//
// Bridging `NSSet` to `Set` and vice versa
// ----------------------------------------
//
// Bridging guarantees for `Set<Element>` are the same as for
// `Dictionary<Element, NSObject>`.
//
/// A collection whose elements are key-value pairs.
///
/// A dictionary is a type of hash table, providing fast access to the entries
/// it contains. Each entry in the table is identified using its key, which is
/// a hashable type such as a string or number. You use that key to retrieve
/// the corresponding value, which can be any object. In other languages,
/// similar data types are known as hashes or associated arrays.
///
/// Create a new dictionary by using a dictionary literal. A dictionary literal
/// is a comma-separated list of key-value pairs, in which a colon separates
/// each key from its associated value, surrounded by square brackets. You can
/// assign a dictionary literal to a variable or constant or pass it to a
/// function that expects a dictionary.
///
/// Here's how you would create a dictionary of HTTP response codes and their
/// related messages:
///
/// var responseMessages = [200: "OK",
/// 403: "Access forbidden",
/// 404: "File not found",
/// 500: "Internal server error"]
///
/// The `responseMessages` variable is inferred to have type `[Int: String]`.
/// The `Key` type of the dictionary is `Int`, and the `Value` type of the
/// dictionary is `String`.
///
/// To create a dictionary with no key-value pairs, use an empty dictionary
/// literal (`[:]`).
///
/// var emptyDict: [String: String] = [:]
///
/// Any type that conforms to the `Hashable` protocol can be used as a
/// dictionary's `Key` type, including all of Swift's basic types. You can use
/// your own custom types as dictionary keys by making them conform to the
/// `Hashable` protocol.
///
/// Getting and Setting Dictionary Values
/// =====================================
///
/// The most common way to access values in a dictionary is to use a key as a
/// subscript. Subscripting with a key takes the following form:
///
/// print(responseMessages[200])
/// // Prints "Optional("OK")"
///
/// Subscripting a dictionary with a key returns an optional value, because a
/// dictionary might not hold a value for the key that you use in the
/// subscript.
///
/// The next example uses key-based subscripting of the `responseMessages`
/// dictionary with two keys that exist in the dictionary and one that does
/// not.
///
/// let httpResponseCodes = [200, 403, 301]
/// for code in httpResponseCodes {
/// if let message = responseMessages[code] {
/// print("Response \(code): \(message)")
/// } else {
/// print("Unknown response \(code)")
/// }
/// }
/// // Prints "Response 200: OK"
/// // Prints "Response 403: Access forbidden"
/// // Prints "Unknown response 301"
///
/// You can also update, modify, or remove keys and values from a dictionary
/// using the key-based subscript. To add a new key-value pair, assign a value
/// to a key that isn't yet a part of the dictionary.
///
/// responseMessages[301] = "Moved permanently"
/// print(responseMessages[301])
/// // Prints "Optional("Moved permanently")"
///
/// Update an existing value by assigning a new value to a key that already
/// exists in the dictionary. If you assign `nil` to an existing key, the key
/// and its associated value are removed. The following example updates the
/// value for the `404` code to be simply "Not found" and removes the
/// key-value pair for the `500` code entirely.
///
/// responseMessages[404] = "Not found"
/// responseMessages[500] = nil
/// print(responseMessages)
/// // Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
///
/// In a mutable `Dictionary` instance, you can modify in place a value that
/// you've accessed through a keyed subscript. The code sample below declares a
/// dictionary called `interestingNumbers` with string keys and values that
/// are integer arrays, then sorts each array in-place in descending order.
///
/// var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
/// "triangular": [1, 3, 6, 10, 15, 21, 28],
/// "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
/// for key in interestingNumbers.keys {
/// interestingNumbers[key]?.sort(by: >)
/// }
///
/// print(interestingNumbers["primes"]!)
/// // Prints "[17, 13, 11, 7, 5, 3, 2]"
///
/// Iterating Over the Contents of a Dictionary
/// ===========================================
///
/// Every dictionary is an unordered collection of key-value pairs. You can
/// iterate over a dictionary using a `for`-`in` loop, decomposing each
/// key-value pair into the elements of a tuple.
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// for (name, path) in imagePaths {
/// print("The path to '\(name)' is '\(path)'.")
/// }
/// // Prints "The path to 'star' is '/glyphs/star.png'."
/// // Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
/// // Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
///
/// The order of key-value pairs in a dictionary is stable between mutations
/// but is otherwise unpredictable. If you need an ordered collection of
/// key-value pairs and don't need the fast key lookup that `Dictionary`
/// provides, see the `KeyValuePairs` type for an alternative.
///
/// You can search a dictionary's contents for a particular value using the
/// `contains(where:)` or `firstIndex(where:)` methods supplied by default
/// implementation. The following example checks to see if `imagePaths` contains
/// any paths in the `"/glyphs"` directory:
///
/// let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
/// if let index = glyphIndex {
/// print("The '\(imagePaths[index].key)' image is a glyph.")
/// } else {
/// print("No glyphs found!")
/// }
/// // Prints "The 'star' image is a glyph."
///
/// Note that in this example, `imagePaths` is subscripted using a dictionary
/// index. Unlike the key-based subscript, the index-based subscript returns
/// the corresponding key-value pair as a non-optional tuple.
///
/// print(imagePaths[glyphIndex!])
/// // Prints "(key: "star", value: "/glyphs/star.png")"
///
/// A dictionary's indices stay valid across additions to the dictionary as
/// long as the dictionary has enough capacity to store the added values
/// without allocating more buffer. When a dictionary outgrows its buffer,
/// existing indices may be invalidated without any notification.
///
/// When you know how many new values you're adding to a dictionary, use the
/// `init(minimumCapacity:)` initializer to allocate the correct amount of
/// buffer.
///
/// Bridging Between Dictionary and NSDictionary
/// ============================================
///
/// You can bridge between `Dictionary` and `NSDictionary` using the `as`
/// operator. For bridging to be possible, the `Key` and `Value` types of a
/// dictionary must be classes, `@objc` protocols, or types that bridge to
/// Foundation types.
///
/// Bridging from `Dictionary` to `NSDictionary` always takes O(1) time and
/// space. When the dictionary's `Key` and `Value` types are neither classes
/// nor `@objc` protocols, any required bridging of elements occurs at the
/// first access of each element. For this reason, the first operation that
/// uses the contents of the dictionary may take O(*n*).
///
/// Bridging from `NSDictionary` to `Dictionary` first calls the `copy(with:)`
/// method (`- copyWithZone:` in Objective-C) on the dictionary to get an
/// immutable copy and then performs additional Swift bookkeeping work that
/// takes O(1) time. For instances of `NSDictionary` that are already
/// immutable, `copy(with:)` usually returns the same dictionary in O(1) time;
/// otherwise, the copying performance is unspecified. The instances of
/// `NSDictionary` and `Dictionary` share buffer using the same copy-on-write
/// optimization that is used when two instances of `Dictionary` share
/// buffer.
@frozen
@_eagerMove
public struct Dictionary<Key: Hashable, Value> {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
public typealias Element = (key: Key, value: Value)
@usableFromInline
internal var _variant: _Variant
@inlinable
internal init(_native: __owned _NativeDictionary<Key, Value>) {
_variant = _Variant(native: _native)
}
#if _runtime(_ObjC)
@inlinable
internal init(_cocoa: __owned __CocoaDictionary) {
_variant = _Variant(cocoa: _cocoa)
}
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSDictionary` is immutable;
/// * `Key` and `Value` are bridged verbatim to Objective-C (i.e.,
/// are reference types).
@inlinable
public // SPI(Foundation)
init(_immutableCocoaDictionary: __owned AnyObject) {
_internalInvariant(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"""
Dictionary can be backed by NSDictionary buffer only when both Key \
and Value are bridged verbatim to Objective-C
""")
self.init(_cocoa: __CocoaDictionary(_immutableCocoaDictionary))
}
#endif
/// Creates an empty dictionary.
@inlinable
public init() {
self.init(_native: _NativeDictionary())
}
/// Creates an empty dictionary with preallocated space for at least the
/// specified number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a dictionary's
/// storage buffer when you know how many key-value pairs you are adding to a
/// dictionary after creation.
///
/// - Parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
public // FIXME(reserveCapacity): Should be inlinable
init(minimumCapacity: Int) {
_variant = _Variant(native: _NativeDictionary(capacity: minimumCapacity))
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// The following example creates a new dictionary using an array of strings
/// as the keys and the integers in a countable range as the values:
///
/// let digitWords = ["one", "two", "three", "four", "five"]
/// let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))
/// print(wordToValue["three"]!)
/// // Prints "3"
/// print(wordToValue)
/// // Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
/// - Precondition: The sequence must not have duplicate keys.
@inlinable
public init<S: Sequence>(
uniqueKeysWithValues keysAndValues: __owned S
) where S.Element == (Key, Value) {
if let d = keysAndValues as? Dictionary<Key, Value> {
self = d
return
}
var native = _NativeDictionary<Key, Value>(
capacity: keysAndValues.underestimatedCount)
// '_MergeError.keyCollision' is caught and handled with an appropriate
// error message one level down, inside native.merge(_:...). We throw an
// error instead of calling fatalError() directly because we want the
// message to include the duplicate key, and the closure only has access to
// the conflicting values.
#if !$Embedded
try! native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })
#else
native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ throws(_MergeError) in
throw _MergeError.keyCollision
}
)
#endif
self.init(_native: native)
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// The following example shows how to choose the first and last values for
/// any duplicate keys:
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["b": 2, "a": 1]
///
/// let lastValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
@inlinable
public init<S: Sequence>(
_ keysAndValues: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
var native = _NativeDictionary<Key, Value>(
capacity: keysAndValues.underestimatedCount)
try native.merge(keysAndValues, isUnique: true, uniquingKeysWith: combine)
self.init(_native: native)
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
/// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
@inlinable
public init<S: Sequence>(
grouping values: __owned S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element] {
try self.init(_native: _NativeDictionary(grouping: values, by: keyForValue))
}
}
//
// All APIs below should dispatch to `_variant`, without doing any
// additional processing.
//
extension Dictionary: Sequence {
/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// for (name, hueValue) in hues {
/// print("The hue of \(name) is \(hueValue).")
/// }
/// // Prints "The hue of Heliotrope is 296."
/// // Prints "The hue of Coral is 16."
/// // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
/// `(key: Key, value: Value)`.
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return _variant.makeIterator()
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
extension Dictionary {
/// Returns a new dictionary containing the key-value pairs of the dictionary
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether the pair
/// should be included in the returned dictionary.
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
@inlinable
@available(swift, introduced: 4.0)
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Key: Value] {
#if _runtime(_ObjC)
guard _variant.isNative else {
// Slow path for bridged dictionaries
var result = _NativeDictionary<Key, Value>()
for element in self {
if try isIncluded(element) {
result.insertNew(key: element.key, value: element.value)
}
}
return Dictionary(_native: result)
}
#endif
return Dictionary(_native: try _variant.asNative.filter(isIncluded))
}
}
extension Dictionary: Collection {
public typealias SubSequence = Slice<Dictionary>
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`. If the dictionary wraps a bridged `NSDictionary`, the
/// performance is unspecified.
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
/// The dictionary's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`; otherwise, the performance is unspecified.
@inlinable
public var endIndex: Index {
return _variant.endIndex
}
@inlinable
public func index(after i: Index) -> Index {
return _variant.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
_variant.formIndex(after: &i)
}
/// Returns the index for the given key.
///
/// If the given key is found in the dictionary, this method returns an index
/// into the dictionary that corresponds with the key-value pair.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// let index = countryCodes.index(forKey: "JP")
///
/// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The index for `key` and its associated value if `key` is in
/// the dictionary; otherwise, `nil`.
@inlinable
@inline(__always)
public func index(forKey key: Key) -> Index? {
// Complexity: amortized O(1) for native dictionary, O(*n*) when wrapping an
// NSDictionary.
return _variant.index(forKey: key)
}
/// Accesses the key-value pair at the specified position.
///
/// This subscript takes an index into the dictionary, instead of a key, and
/// returns the corresponding key-value pair as a tuple. When performing
/// collection-based operations that return an index into a dictionary, use
/// this subscript with the resulting value.
///
/// For example, to find the key for a particular value in a dictionary, use
/// the `firstIndex(where:)` method.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) {
/// print(countryCodes[index])
/// print("Japan's country code is '\(countryCodes[index].key)'.")
/// } else {
/// print("Didn't find 'Japan' as a value in the dictionary.")
/// }
/// // Prints "(key: "JP", value: "Japan")"
/// // Prints "Japan's country code is 'JP'."
///
/// - Parameter position: The position of the key-value pair to access.
/// `position` must be a valid index of the dictionary and not equal to
/// `endIndex`.
/// - Returns: A two-element tuple with the key and value corresponding to
/// `position`.
@inlinable
public subscript(position: Index) -> Element {
return _variant.lookup(position)
}
/// The number of key-value pairs in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
//
// `Sequence` conformance
//
/// A Boolean value that indicates whether the dictionary is empty.
///
/// Dictionaries are empty when created with an initializer or an empty
/// dictionary literal.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.isEmpty)
/// // Prints "true"
@inlinable
public var isEmpty: Bool {
return count == 0
}
}
extension Dictionary {
/// Accesses the value associated with the given key for reading and writing.
///
/// This *key-based* subscript returns the value for the given key if the key
/// is found in the dictionary, or `nil` if the key is not found.
///
/// The following example creates a new dictionary and prints the value of a
/// key found in the dictionary (`"Coral"`) and a key not found in the
/// dictionary (`"Cerise"`).
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// print(hues["Coral"])
/// // Prints "Optional(16)"
/// print(hues["Cerise"])
/// // Prints "nil"
///
/// When you assign a value for a key and that key already exists, the
/// dictionary overwrites the existing value. If the dictionary doesn't
/// contain the key, the key and value are added as a new key-value pair.
///
/// Here, the value for the key `"Coral"` is updated from `16` to `18` and a
/// new key-value pair is added for the key `"Cerise"`.
///
/// hues["Coral"] = 18
/// print(hues["Coral"])
/// // Prints "Optional(18)"
///
/// hues["Cerise"] = 330
/// print(hues["Cerise"])
/// // Prints "Optional(330)"
///
/// If you assign `nil` as the value for the given key, the dictionary
/// removes that key and its associated value.
///
/// In the following example, the key-value pair for the key `"Aquamarine"`
/// is removed from the dictionary by assigning `nil` to the key-based
/// subscript.
///
/// hues["Aquamarine"] = nil
/// print(hues)
/// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The value associated with `key` if `key` is in the dictionary;
/// otherwise, `nil`.
@inlinable
public subscript(key: Key) -> Value? {
get {
return _variant.lookup(key)
}
set(newValue) {
if let x = newValue {
_variant.setValue(x, forKey: key)
} else {
removeValue(forKey: key)
}
}
_modify {
defer { _fixLifetime(self) }
yield &_variant[key]
}
}
}
extension Dictionary: ExpressibleByDictionaryLiteral {
/// Creates a dictionary initialized with a dictionary literal.
///
/// Do not call this initializer directly. It is called by the compiler to
/// handle dictionary literals. To use a dictionary literal as the initial
/// value of a dictionary, enclose a comma-separated list of key-value pairs
/// in square brackets.
///
/// For example, the code sample below creates a dictionary with string keys
/// and values.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// - Parameter elements: The key-value pairs that will make up the new
/// dictionary. Each key in `elements` must be unique.
@inlinable
@_semantics("optimize.sil.specialize.generic.size.never")
public init(dictionaryLiteral elements: (Key, Value)...) {
let native = _NativeDictionary<Key, Value>(capacity: elements.count)
for (key, value) in elements {
let (bucket, found) = native.find(key)
_precondition(!found, "Dictionary literal contains duplicate keys")
native._insert(at: bucket, key: key, value: value)
}
self.init(_native: native)
}
}
extension Dictionary {
/// Accesses the value with the given key, falling back to the given default
/// value if the key isn't found.
///
/// Use this subscript when you want either the value for a particular key
/// or, when that key is not present in the dictionary, a default value. This
/// example uses the subscript with a message to use in case an HTTP response
/// code isn't recognized:
///
/// var responseMessages = [200: "OK",
/// 403: "Access forbidden",
/// 404: "File not found",
/// 500: "Internal server error"]
///
/// let httpResponseCodes = [200, 403, 301]
/// for code in httpResponseCodes {
/// let message = responseMessages[code, default: "Unknown response"]
/// print("Response \(code): \(message)")
/// }
/// // Prints "Response 200: OK"
/// // Prints "Response 403: Access forbidden"
/// // Prints "Response 301: Unknown response"
///
/// When a dictionary's `Value` type has value semantics, you can use this
/// subscript to perform in-place operations on values in the dictionary.
/// The following example uses this subscript while counting the occurrences
/// of each letter in a string:
///
/// let message = "Hello, Elle!"
/// var letterCounts: [Character: Int] = [:]
/// for letter in message {
/// letterCounts[letter, default: 0] += 1
/// }
/// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
///
/// When `letterCounts[letter, default: 0] += 1` is executed with a
/// value of `letter` that isn't already a key in `letterCounts`, the
/// specified default value (`0`) is returned from the subscript,
/// incremented, and then added to the dictionary under that key.
///
/// - Note: Do not use this subscript to modify dictionary values if the
/// dictionary's `Value` type is a class. In that case, the default value
/// and key are not written back to the dictionary after an operation.
///
/// - Parameters:
/// - key: The key the look up in the dictionary.
/// - defaultValue: The default value to use if `key` doesn't exist in the
/// dictionary.
/// - Returns: The value associated with `key` in the dictionary; otherwise,
/// `defaultValue`.
@inlinable
public subscript(
key: Key, default defaultValue: @autoclosure () -> Value
) -> Value {
@inline(__always)
get {
return _variant.lookup(key) ?? defaultValue()
}
@inline(__always)
_modify {
let (bucket, found) = _variant.mutatingFind(key)
let native = _variant.asNative
if !found {
let value = defaultValue()
native._insert(at: bucket, key: key, value: value)
}
let address = unsafe native._values + bucket.offset
defer { _fixLifetime(self) }
yield unsafe &address.pointee
}
}
/// Returns a new dictionary containing the keys of this dictionary with the
/// values transformed by the given closure.
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns a
/// transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and transformed values of
/// this dictionary.
///
/// - Complexity: O(*n*), where *n* is the length of the dictionary.
@inlinable
public func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> Dictionary<Key, T> {
return try Dictionary<Key, T>(_native: _variant.mapValues(transform))
}
/// Returns a new dictionary containing only the key-value pairs that have
/// non-`nil` values as the result of transformation by the given closure.
///
/// Use this method to receive a dictionary with non-optional values when
/// your transformation produces optional values.
///
/// In this example, note the difference in the result of using `mapValues`
/// and `compactMapValues` with a transformation that returns an optional
/// `Int` value.
///
/// let data = ["a": "1", "b": "three", "c": "///4///"]
///
/// let m: [String: Int?] = data.mapValues { str in Int(str) }
/// // ["a": Optional(1), "b": nil, "c": nil]
///
/// let c: [String: Int] = data.compactMapValues { str in Int(str) }
/// // ["a": 1]
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns an
/// optional transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and non-`nil` transformed
/// values of this dictionary.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of the original
/// dictionary and *m* is the length of the resulting dictionary.
@inlinable
public func compactMapValues<T>(
_ transform: (Value) throws -> T?
) rethrows -> Dictionary<Key, T> {
let result: _NativeDictionary<Key, T> =
try self.reduce(into: _NativeDictionary<Key, T>()) { (result, element) in
if let value = try transform(element.value) {
result.insertNew(key: element.key, value: value)
}
}
return Dictionary<Key, T>(_native: result)
}
/// Updates the value stored in the dictionary for the given key, or adds a
/// new key-value pair if the key does not exist.
///
/// Use this method instead of key-based subscripting when you need to know
/// whether the new value supplants the value of an existing key. If the
/// value of an existing key is updated, `updateValue(_:forKey:)` returns
/// the original value.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
///
/// if let oldValue = hues.updateValue(18, forKey: "Coral") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// }
/// // Prints "The old value of 16 was replaced with a new one."
///
/// If the given key is not present in the dictionary, this method adds the
/// key-value pair and returns `nil`.
///
/// if let oldValue = hues.updateValue(330, forKey: "Cerise") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// } else {
/// print("No value was found in the dictionary for that key.")
/// }
/// // Prints "No value was found in the dictionary for that key."
///
/// - Parameters: