Skip to content

Commit 5285c22

Browse files
authored
Merge pull request #76846 from swiftlang/egorzhdan/std-map-by-literal
[cxx-interop] Conform `std::map` to `ExpressibleByDictionaryLiteral`
2 parents 90e4a98 + 535a941 commit 5285c22

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

stdlib/public/Cxx/CxxDictionary.swift

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
///
1515
/// C++ standard library types such as `std::map` and `std::unordered_map`
1616
/// conform to this protocol.
17-
public protocol CxxDictionary<Key, Value> {
18-
associatedtype Key
19-
associatedtype Value
17+
public protocol CxxDictionary<Key, Value>: ExpressibleByDictionaryLiteral {
18+
override associatedtype Key
19+
override associatedtype Value
2020
associatedtype Element: CxxPair<Key, Value>
2121
associatedtype RawIterator: UnsafeCxxInputIterator
2222
where RawIterator.Pointee == Element
@@ -65,6 +65,14 @@ extension CxxDictionary {
6565
}
6666
}
6767

68+
@inlinable
69+
public init(dictionaryLiteral elements: (Key, Value)...) {
70+
self.init()
71+
for (key, value) in elements {
72+
self[key] = value
73+
}
74+
}
75+
6876
@inlinable
6977
public subscript(key: Key) -> Value? {
7078
get {

test/Interop/Cxx/stdlib/use-std-map.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,35 @@ StdMapTestSuite.test("MapStrings.init(_: Dictionary<std.string, std.string>)") {
7171
expectEqual(emptyM.size(), 0)
7272
}
7373

74+
StdMapTestSuite.test("Map as ExpressibleByDictionaryLiteral") {
75+
let m: Map = [-1 : 2, 2 : 3, 33 : 44]
76+
expectEqual(m.size(), 3)
77+
78+
func takesMap(_ m: Map) {
79+
expectEqual(m[-1], 2)
80+
expectEqual(m[2], 3)
81+
expectEqual(m[33], 44)
82+
}
83+
84+
takesMap(m)
85+
takesMap([-1 : 2, 2 : 3, 33 : 44])
86+
}
87+
88+
/// Same as above, but for std::unordered_map.
89+
StdMapTestSuite.test("UnorderedMap as ExpressibleByDictionaryLiteral") {
90+
let m: UnorderedMap = [-1 : 2, 2 : 3, 33 : 44]
91+
expectEqual(m.size(), 3)
92+
93+
func takesUnorderedMap(_ m: UnorderedMap) {
94+
expectEqual(m[-1], 2)
95+
expectEqual(m[2], 3)
96+
expectEqual(m[33], 44)
97+
}
98+
99+
takesUnorderedMap(m)
100+
takesUnorderedMap([-1 : 2, 2 : 3, 33 : 44])
101+
}
102+
74103
StdMapTestSuite.test("Map.subscript") {
75104
// This relies on the `std::map` conformance to `CxxDictionary` protocol.
76105
var m = initMap()

0 commit comments

Comments
 (0)