Skip to content

Commit 4692242

Browse files
Added conditional conformance fo Equatable and Hashable for DictionaryLiteral. Added tests too.
1 parent 8d3049d commit 4692242

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

stdlib/public/core/Mirror.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,43 @@ extension DictionaryLiteral : RandomAccessCollection {
905905
}
906906
}
907907

908+
extension DictionaryLiteral : Equatable where Key: Equatable, Value : Equatable {
909+
@_inlineable // FIXME(sil-serialize-all)
910+
public static func ==(lhs: DictionaryLiteral<Key, Value>, rhs: DictionaryLiteral<Key, Value>) -> Bool {
911+
let lhsCount = lhs.count
912+
if lhsCount != rhs.count {
913+
return false
914+
}
915+
// We know that lhs.count == rhs.count, compare element wise.
916+
for idx in 0..<lhsCount {
917+
if lhs[idx].key != rhs[idx].key ||
918+
lhs[idx].value != rhs[idx].value {
919+
return false
920+
}
921+
}
922+
return true
923+
}
924+
}
925+
926+
extension DictionaryLiteral : Hashable where Key: Hashable, Value : Hashable {
927+
/// The hash value for the dictionary.
928+
///
929+
/// Two dictionaries that are equal will always have equal hash values.
930+
///
931+
/// Hash values are not guaranteed to be equal across different executions of
932+
/// your program. Do not save hash values to use during a future execution.
933+
@_inlineable // FIXME(sil-serialize-all)
934+
public var hashValue: Int {
935+
// FIXME(ABI)#177: <rdar://problem/18915294> Issue applies to DictionaryLiteral too
936+
var result: Int = 0
937+
for element in self {
938+
let elementHashValue = _combineHashValues(element.key.hashValue, element.value.hashValue)
939+
result = _combineHashValues(result, elementHashValue)
940+
}
941+
return result
942+
}
943+
}
944+
908945
extension String {
909946
/// Creates a string representing the given value.
910947
///

test/stdlib/DictionaryLiteral.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,12 @@ expectType(DictionaryLiteral<String, NSObject>.self, &hetero1)
5454

5555
var hetero2: DictionaryLiteral = ["a": 1 as NSNumber, "b": "Foo" as NSString]
5656
expectType(DictionaryLiteral<String, NSObject>.self, &hetero2)
57+
58+
let instances: [DictionaryLiteral<Int, String>] = [
59+
[1: "a", 1: "a", 2: "b"],
60+
[1: "a", 2: "b", 1: "a"],
61+
[2: "b", 1: "a", 1: "a"],
62+
[1: "a", 1: "a", 1: "a"]
63+
]
64+
checkEquatable(instances, oracle: { $0 == $1 })
65+
checkHashable(instances, equalityOracle: { $0 == $1 })

0 commit comments

Comments
 (0)