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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
|
//===----------------------------------------------------------------------===//
//
// 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.
try! native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })
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 = native._values + bucket.offset
defer { _fixLifetime(self) }
yield &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:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with `value`. If `key` already exists in
/// the dictionary, `value` replaces the existing associated value. If
/// `key` isn't already a key of the dictionary, the `(key, value)` pair
/// is added.
/// - Returns: The value that was replaced, or `nil` if a new key-value pair
/// was added.
@inlinable
@discardableResult
public mutating func updateValue(
_ value: __owned Value,
forKey key: Key
) -> Value? {
return _variant.updateValue(value, forKey: key)
}
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge<S: Sequence>(
_ other: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
try _variant.merge(other, uniquingKeysWith: combine)
}
/// Merges the given dictionary into this dictionary, using a combining
/// closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-values
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge(
_ other: __owned [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows {
try _variant.merge(
other.lazy.map { ($0, $1) }, uniquingKeysWith: combine)
}
/// Creates a dictionary by merging key-value pairs in a sequence into the
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable
public __consuming func merging<S: Sequence>(
_ other: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] where S.Element == (Key, Value) {
var result = self
try result._variant.merge(other, uniquingKeysWith: combine)
return result
}
/// Creates a dictionary by merging the given dictionary into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let otherDictionary = ["a": 3, "b": 4]
///
/// let keepingCurrent = dictionary.merging(otherDictionary)
/// { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(otherDictionary)
/// { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable
public __consuming func merging(
_ other: __owned [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] {
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
/// Removes and returns the key-value pair at the specified index.
///
/// Calling this method invalidates any existing indices for use with this
/// dictionary.
///
/// - Parameter index: The position of the key-value pair to remove. `index`
/// must be a valid index of the dictionary, and must not equal the
/// dictionary's end index.
/// - Returns: The key-value pair that correspond to `index`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
@discardableResult
public mutating func remove(at index: Index) -> Element {
return _variant.remove(at: index)
}
/// Removes the given key and its associated value from the dictionary.
///
/// If the key is found in the dictionary, this method returns the key's
/// associated value. On removal, this method invalidates all indices with
/// respect to the dictionary.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// if let value = hues.removeValue(forKey: "Coral") {
/// print("The value \(value) was removed.")
/// }
/// // Prints "The value 16 was removed."
///
/// If the key isn't found in the dictionary, `removeValue(forKey:)` returns
/// `nil`.
///
/// if let value = hues.removeValue(forKey: "Cerise") {
/// print("The value \(value) was removed.")
/// } else {
/// print("No value found for that key.")
/// }
/// // Prints "No value found for that key.""
///
/// - Parameter key: The key to remove along with its associated value.
/// - Returns: The value that was removed, or `nil` if the key was not
/// present in the dictionary.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
return _variant.removeValue(forKey: key)
}
/// Removes all key-value pairs from the dictionary.
///
/// Calling this method invalidates all indices with respect to the
/// dictionary.
///
/// - Parameter keepCapacity: Whether the dictionary should keep its
/// underlying buffer. If you pass `true`, the operation preserves the
/// buffer capacity that the collection has, otherwise the underlying
/// buffer is released. The default is `false`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
// The 'will not decrease' part in the documentation comment is worded very
// carefully. The capacity can increase if we replace Cocoa dictionary with
// native dictionary.
_variant.removeAll(keepingCapacity: keepCapacity)
}
}
extension Dictionary {
/// A collection containing just the keys of the dictionary.
///
/// When iterated over, keys appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs. Each key in the keys
/// collection has a unique value.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for k in countryCodes.keys {
/// print(k)
/// }
/// // Prints "BR"
/// // Prints "JP"
/// // Prints "GH"
@inlinable
@available(swift, introduced: 4.0)
public var keys: Keys {
// FIXME(accessors): Provide a _read
get {
return Keys(_dictionary: self)
}
}
/// A collection containing just the values of the dictionary.
///
/// When iterated over, values appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for v in countryCodes.values {
/// print(v)
/// }
/// // Prints "Brazil"
/// // Prints "Japan"
/// // Prints "Ghana"
@inlinable
@available(swift, introduced: 4.0)
public var values: Values {
// FIXME(accessors): Provide a _read
get {
return Values(_dictionary: self)
}
_modify {
var values = Values(_variant: _Variant(dummy: ()))
swap(&values._variant, &_variant)
defer { self._variant = values._variant }
yield &values
}
}
/// A view of a dictionary's keys.
@frozen
public struct Keys: Collection, Equatable {
public typealias Element = Key
public typealias SubSequence = Slice<Dictionary.Keys>
@usableFromInline
internal var _variant: Dictionary<Key, Value>._Variant
@inlinable
internal init(_dictionary: __owned Dictionary) {
self._variant = _dictionary._variant
}
// Collection Conformance
// ----------------------
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
@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)
}
@inlinable
public subscript(position: Index) -> Element {
return _variant.key(at: position)
}
// Customization
// -------------
/// The number of keys in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
@inlinable
public var isEmpty: Bool {
return count == 0
}
@inlinable
@inline(__always)
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return _variant.contains(element)
}
@inlinable
@inline(__always)
public func _customIndexOfEquatableElement(_ element: Element) -> Index?? {
return Optional(_variant.index(forKey: element))
}
@inlinable
@inline(__always)
public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(element)
}
@inlinable
public static func ==(lhs: Keys, rhs: Keys) -> Bool {
// Equal if the two dictionaries share storage.
#if _runtime(_ObjC)
if
lhs._variant.isNative,
rhs._variant.isNative,
lhs._variant.asNative._storage === rhs._variant.asNative._storage
{
return true
}
if
!lhs._variant.isNative,
!rhs._variant.isNative,
lhs._variant.asCocoa.object === rhs._variant.asCocoa.object
{
return true
}
#else
if lhs._variant.asNative._storage === rhs._variant.asNative._storage {
return true
}
#endif
// Not equal if the dictionaries are different sizes.
if lhs.count != rhs.count {
return false
}
// Perform unordered comparison of keys.
for key in lhs {
if !rhs.contains(key) {
return false
}
}
return true
}
}
/// A view of a dictionary's values.
@frozen
public struct Values: MutableCollection {
public typealias Element = Value
@usableFromInline
internal var _variant: Dictionary<Key, Value>._Variant
@inlinable
internal init(_variant: __owned Dictionary<Key, Value>._Variant) {
self._variant = _variant
}
@inlinable
internal init(_dictionary: __owned Dictionary) {
self._variant = _dictionary._variant
}
// Collection Conformance
// ----------------------
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
@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)
}
@inlinable
public subscript(position: Index) -> Element {
// FIXME(accessors): Provide a _read
get {
return _variant.value(at: position)
}
_modify {
let native = _variant.ensureUniqueNative()
let bucket = native.validatedBucket(for: position)
let address = native._values + bucket.offset
defer { _fixLifetime(self) }
yield &address.pointee
}
}
// Customization
// -------------
/// The number of values in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
@inlinable
public var isEmpty: Bool {
return count == 0
}
@inlinable
public mutating func swapAt(_ i: Index, _ j: Index) {
guard i != j else { return }
#if _runtime(_ObjC)
if !_variant.isNative {
_variant = .init(native: _NativeDictionary(_variant.asCocoa))
}
#endif
let isUnique = _variant.isUniquelyReferenced()
let native = _variant.asNative
let a = native.validatedBucket(for: i)
let b = native.validatedBucket(for: j)
_variant.asNative.swapValuesAt(a, b, isUnique: isUnique)
}
}
}
@_unavailableInEmbedded
extension Dictionary.Keys
: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _makeCollectionDescription()
}
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "Dictionary.Keys")
}
}
@_unavailableInEmbedded
extension Dictionary.Values
: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _makeCollectionDescription()
}
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "Dictionary.Values")
}
}
extension Dictionary.Keys {
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _base: Dictionary<Key, Value>.Iterator
@inlinable
@inline(__always)
internal init(_ base: Dictionary<Key, Value>.Iterator) {
self._base = base
}
@inlinable
@inline(__always)
public mutating func next() -> Key? {
#if _runtime(_ObjC)
if case .cocoa(let cocoa) = _base._variant {
_base._cocoaPath()
guard let cocoaKey = cocoa.nextKey() else { return nil }
return _forceBridgeFromObjectiveC(cocoaKey, Key.self)
}
#endif
return _base._asNative.nextKey()
}
}
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_variant.makeIterator())
}
}
extension Dictionary.Values {
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _base: Dictionary<Key, Value>.Iterator
@inlinable
@inline(__always)
internal init(_ base: Dictionary<Key, Value>.Iterator) {
self._base = base
}
@inlinable
@inline(__always)
public mutating func next() -> Value? {
#if _runtime(_ObjC)
if case .cocoa(let cocoa) = _base._variant {
_base._cocoaPath()
guard let (_, cocoaValue) = cocoa.next() else { return nil }
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return _base._asNative.nextValue()
}
}
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_variant.makeIterator())
}
}
extension Dictionary: Equatable where Value: Equatable {
@inlinable
public static func == (lhs: [Key: Value], rhs: [Key: Value]) -> Bool {
#if _runtime(_ObjC)
switch (lhs._variant.isNative, rhs._variant.isNative) {
case (true, true):
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
case (false, false):
return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa)
case (true, false):
return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa)
case (false, true):
return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa)
}
#else
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
#endif
}
}
extension Dictionary: Hashable where Value: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
for (k, v) in self {
// Note that we use a copy of our own hasher here. This makes hash values
// dependent on its state, eliminating static collision patterns.
var elementHasher = hasher
elementHasher.combine(k)
elementHasher.combine(v)
commutativeHash ^= elementHasher._finalize()
}
hasher.combine(commutativeHash)
}
}
@_unavailableInEmbedded
extension Dictionary: _HasCustomAnyHashableRepresentation
where Value: Hashable {
public __consuming func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(_box: _DictionaryAnyHashableBox(self))
}
}
@_unavailableInEmbedded
internal struct _DictionaryAnyHashableBox<Key: Hashable, Value: Hashable>
: _AnyHashableBox {
internal let _value: Dictionary<Key, Value>
internal let _canonical: Dictionary<AnyHashable, AnyHashable>
internal init(_ value: __owned Dictionary<Key, Value>) {
self._value = value
self._canonical = value as Dictionary<AnyHashable, AnyHashable>
}
internal var _base: Any {
return _value
}
internal var _canonicalBox: _AnyHashableBox {
return _DictionaryAnyHashableBox<AnyHashable, AnyHashable>(_canonical)
}
internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
guard
let other = other as? _DictionaryAnyHashableBox<AnyHashable, AnyHashable>
else {
return nil
}
return _canonical == other._value
}
internal var _hashValue: Int {
return _canonical.hashValue
}
internal func _hash(into hasher: inout Hasher) {
_canonical.hash(into: &hasher)
}
internal func _rawHashValue(_seed: Int) -> Int {
return _canonical._rawHashValue(seed: _seed)
}
internal func _unbox<T: Hashable>() -> T? {
return _value as? T
}
internal func _downCastConditional<T>(
into result: UnsafeMutablePointer<T>
) -> Bool {
guard let value = _value as? T else { return false }
result.initialize(to: value)
return true
}
}
@_unavailableInEmbedded
extension Collection {
// Utility method for KV collections that wish to implement
// CustomStringConvertible and CustomDebugStringConvertible using a bracketed
// list of elements.
// FIXME: Doesn't use the withTypeName argument yet
internal func _makeKeyValuePairDescription<K, V>(
withTypeName type: String? = nil
) -> String where Element == (key: K, value: V) {
#if !SWIFT_STDLIB_STATIC_PRINT
if self.isEmpty {
return "[:]"
}
var result = "["
var first = true
for (k, v) in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(k, terminator: "", to: &result)
result += ": "
debugPrint(v, terminator: "", to: &result)
}
result += "]"
return result
#else
return "(collection printing not available)"
#endif
}
}
@_unavailableInEmbedded
extension Dictionary: CustomStringConvertible, CustomDebugStringConvertible {
/// A string that represents the contents of the dictionary.
public var description: String {
return _makeKeyValuePairDescription()
}
/// A string that represents the contents of the dictionary, suitable for
/// debugging.
public var debugDescription: String {
return _makeKeyValuePairDescription()
}
}
@usableFromInline
@frozen
internal enum _MergeError: Error {
case keyCollision
}
extension Dictionary {
/// The position of a key-value pair in a dictionary.
///
/// Dictionary has two subscripting interfaces:
///
/// 1. Subscripting with a key, yielding an optional value:
///
/// v = d[k]!
///
/// 2. Subscripting with an index, yielding a key-value pair:
///
/// (k, v) = d[i]
@frozen
public struct Index {
// Index for native dictionary is efficient. Index for bridged NSDictionary
// is not, because neither NSEnumerator nor fast enumeration support moving
// backwards. Even if they did, there is another issue: NSEnumerator does
// not support NSCopying, and fast enumeration does not document that it is
// safe to copy the state. So, we cannot implement Index that is a value
// type for bridged NSDictionary in terms of Cocoa enumeration facilities.
@frozen
@usableFromInline
internal enum _Variant {
case native(_HashTable.Index)
#if _runtime(_ObjC)
case cocoa(__CocoaDictionary.Index)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
@inline(__always)
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
@inline(__always)
internal init(_native index: _HashTable.Index) {
self.init(_variant: .native(index))
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
internal init(_cocoa index: __owned __CocoaDictionary.Index) {
self.init(_variant: .cocoa(index))
}
#endif
}
}
extension Dictionary.Index._Variant: @unchecked Sendable {}
extension Dictionary.Index {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
// Allow the optimizer to consider the surrounding code unreachable if Element
// is guaranteed to be native.
@usableFromInline @_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
@inlinable
@inline(__always)
internal mutating func _isUniquelyReferenced() -> Bool {
defer { _fixLifetime(self) }
var handle = _asCocoa.handleBitPattern
return handle == 0 || _isUnique_native(&handle)
}
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _HashTable.Index {
switch _variant {
case .native(let nativeIndex):
return nativeIndex
#if _runtime(_ObjC)
case .cocoa:
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
#endif
}
}
#if _runtime(_ObjC)
@usableFromInline
internal var _asCocoa: __CocoaDictionary.Index {
@_transparent
get {
switch _variant {
case .native:
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
case .cocoa(let cocoaIndex):
return cocoaIndex
}
}
_modify {
guard case .cocoa(var cocoa) = _variant else {
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
}
let dummy = _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0)
_variant = .native(dummy)
defer { _variant = .cocoa(cocoa) }
yield &cocoa
}
}
#endif
}
extension Dictionary.Index: Equatable {
@inlinable
public static func == (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative == rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa == rhsCocoa
default:
_preconditionFailure("Comparing indexes from different dictionaries")
#endif
}
}
}
extension Dictionary.Index: Comparable {
@inlinable
public static func < (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative < rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa < rhsCocoa
default:
_preconditionFailure("Comparing indexes from different dictionaries")
#endif
}
}
}
extension Dictionary.Index: Hashable {
public // FIXME(cocoa-index): Make inlinable
func hash(into hasher: inout Hasher) {
#if _runtime(_ObjC)
guard _isNative else {
hasher.combine(1 as UInt8)
hasher.combine(_asCocoa._offset)
return
}
hasher.combine(0 as UInt8)
hasher.combine(_asNative.bucket.offset)
#else
hasher.combine(_asNative.bucket.offset)
#endif
}
}
extension Dictionary {
/// An iterator over the members of a `Dictionary<Key, Value>`.
@frozen
public struct Iterator {
// Dictionary has a separate IteratorProtocol and Index because of
// efficiency and implementability reasons.
//
// Native dictionaries have efficient indices.
// Bridged NSDictionary instances don't.
//
// Even though fast enumeration is not suitable for implementing
// Index, which is multi-pass, it is suitable for implementing a
// IteratorProtocol, which is being consumed as iteration proceeds.
@usableFromInline
@frozen
internal enum _Variant {
case native(_NativeDictionary<Key, Value>.Iterator)
#if _runtime(_ObjC)
case cocoa(__CocoaDictionary.Iterator)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
internal init(_native: __owned _NativeDictionary<Key, Value>.Iterator) {
self.init(_variant: .native(_native))
}
#if _runtime(_ObjC)
@inlinable
internal init(_cocoa: __owned __CocoaDictionary.Iterator) {
self.init(_variant: .cocoa(_cocoa))
}
#endif
}
}
extension Dictionary.Iterator._Variant: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Iterator {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
/// Allow the optimizer to consider the surrounding code unreachable if
/// Dictionary<Key, Value> is guaranteed to be native.
@usableFromInline @_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _NativeDictionary<Key, Value>.Iterator {
get {
switch _variant {
case .native(let nativeIterator):
return nativeIterator
#if _runtime(_ObjC)
case .cocoa:
_internalInvariantFailure("internal error: does not contain a native index")
#endif
}
}
set {
self._variant = .native(newValue)
}
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _asCocoa: __CocoaDictionary.Iterator {
get {
switch _variant {
case .native:
_internalInvariantFailure("internal error: does not contain a Cocoa index")
case .cocoa(let cocoa):
return cocoa
}
}
}
#endif
}
extension Dictionary.Iterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
@inline(__always)
public mutating func next() -> (key: Key, value: Value)? {
#if _runtime(_ObjC)
guard _isNative else {
if let (cocoaKey, cocoaValue) = _asCocoa.next() {
let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)
return (nativeKey, nativeValue)
}
return nil
}
#endif
return _asNative.next()
}
}
#if SWIFT_ENABLE_REFLECTION
extension Dictionary.Iterator: CustomReflectable {
/// A mirror that reflects the iterator.
public var customMirror: Mirror {
return Mirror(
self,
children: EmptyCollection<(label: String?, value: Any)>())
}
}
extension Dictionary: CustomReflectable {
/// A mirror that reflects the dictionary.
public var customMirror: Mirror {
let style = Mirror.DisplayStyle.dictionary
return Mirror(self, unlabeledChildren: self, displayStyle: style)
}
}
#endif
extension Dictionary {
/// Removes and returns the first key-value pair of the dictionary if the
/// dictionary isn't empty.
///
/// The first element of the dictionary is not necessarily the first element
/// added. Don't expect any particular ordering of key-value pairs.
///
/// - Returns: The first key-value pair of the dictionary if the dictionary
/// is not empty; otherwise, `nil`.
///
/// - Complexity: Averages to O(1) over many calls to `popFirst()`.
@inlinable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
}
/// The total number of key-value pairs that the dictionary can contain without
/// allocating new storage.
@inlinable
public var capacity: Int {
return _variant.capacity
}
/// Reserves enough space to store the specified number of key-value pairs.
///
/// If you are adding a known number of key-value pairs to a dictionary, use this
/// method to avoid multiple reallocations. This method ensures that the
/// dictionary has unique, mutable, contiguous storage, with space allocated
/// for at least the requested number of key-value pairs.
///
/// Calling the `reserveCapacity(_:)` method on a dictionary with bridged
/// storage triggers a copy to contiguous storage even if the existing
/// storage has room to store `minimumCapacity` key-value pairs.
///
/// - Parameter minimumCapacity: The requested number of key-value pairs to
/// store.
public // FIXME(reserveCapacity): Should be inlinable
mutating func reserveCapacity(_ minimumCapacity: Int) {
_variant.reserveCapacity(minimumCapacity)
_internalInvariant(self.capacity >= minimumCapacity)
}
}
public typealias DictionaryIndex<Key: Hashable, Value> =
Dictionary<Key, Value>.Index
public typealias DictionaryIterator<Key: Hashable, Value> =
Dictionary<Key, Value>.Iterator
extension Dictionary: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Keys: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Values: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Keys.Iterator: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Values.Iterator: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Index: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
extension Dictionary.Iterator: @unchecked Sendable
where Key: Sendable, Value: Sendable {}
|