Skip to content

Commit 8e2f0e2

Browse files
authored
Merge pull request #75877 from swiftlang/egorzhdan/std-map-init
[cxx-interop] Allow initializing `std::map` from Swift Dictionary
2 parents 915b531 + 9fe13ec commit 8e2f0e2

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

stdlib/public/Cxx/CxxDictionary.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,20 @@ public protocol CxxDictionary<Key, Value> {
5151
}
5252

5353
extension CxxDictionary {
54+
/// Creates a C++ map containing the elements of a Swift Dictionary.
55+
///
56+
/// This initializes the map by copying every key and value of the dictionary.
57+
///
58+
/// - Complexity: O(*n*), where *n* is the number of entries in the Swift
59+
/// dictionary
60+
@inlinable
61+
public init(_ dictionary: Dictionary<Key, Value>) where Key: Hashable {
62+
self.init()
63+
for (key, value) in dictionary {
64+
self[key] = value
65+
}
66+
}
67+
5468
@inlinable
5569
public subscript(key: Key) -> Value? {
5670
get {

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,49 @@ StdMapTestSuite.test("init") {
2828
expectTrue(m.empty())
2929
}
3030

31+
StdMapTestSuite.test("Map.init(_: Dictionary<Int, Int>)") {
32+
let swiftDict: [Int32 : Int32] = [-1: 2, 2: 3, 33: 44]
33+
let m = Map(swiftDict)
34+
expectEqual(m.size(), 3)
35+
36+
expectEqual(m[-1], 2)
37+
expectEqual(m[2], 3)
38+
expectEqual(m[33], 44)
39+
40+
let emptySwiftDict: [Int32 : Int32] = [:]
41+
let emptyM = Map(emptySwiftDict)
42+
expectEqual(emptyM.size(), 0)
43+
}
44+
45+
/// Same as above, but for std::unordered_map.
46+
StdMapTestSuite.test("UnorderedMap.init(_: Dictionary<Int, Int>)") {
47+
let swiftDict: [Int32 : Int32] = [-1 : 2, 2 : 3, 33 : 44]
48+
let m = UnorderedMap(swiftDict)
49+
expectEqual(m.size(), 3)
50+
51+
expectEqual(m[-1], 2)
52+
expectEqual(m[2], 3)
53+
expectEqual(m[33], 44)
54+
55+
let emptySwiftDict: [Int32 : Int32] = [:]
56+
let emptyM = UnorderedMap(emptySwiftDict)
57+
expectEqual(emptyM.size(), 0)
58+
}
59+
60+
StdMapTestSuite.test("MapStrings.init(_: Dictionary<std.string, std.string>)") {
61+
let swiftDict = [std.string("abc") : std.string("123"),
62+
std.string() : std.string("empty")]
63+
let m = MapStrings(swiftDict)
64+
expectEqual(m.size(), 2)
65+
66+
expectEqual(m[std.string("abc")], std.string("123"))
67+
expectEqual(m[std.string()], std.string("empty"))
68+
69+
let emptySwiftDict: [std.string : std.string] = [:]
70+
let emptyM = MapStrings(emptySwiftDict)
71+
expectEqual(emptyM.size(), 0)
72+
}
73+
3174
StdMapTestSuite.test("Map.subscript") {
3275
// This relies on the `std::map` conformance to `CxxDictionary` protocol.
3376
var m = initMap()

0 commit comments

Comments
 (0)