Skip to content

Commit

Permalink
Added conditional conformance fo Equatable and Hashable for Dictionar…
Browse files Browse the repository at this point in the history
…yLiteral. Added tests too.
  • Loading branch information
mortenbekditlevsen committed Feb 6, 2018
1 parent 8d3049d commit 4692242
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
37 changes: 37 additions & 0 deletions stdlib/public/core/Mirror.swift
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,43 @@ extension DictionaryLiteral : RandomAccessCollection {
}
}

extension DictionaryLiteral : Equatable where Key: Equatable, Value : Equatable {
@_inlineable // FIXME(sil-serialize-all)
public static func ==(lhs: DictionaryLiteral<Key, Value>, rhs: DictionaryLiteral<Key, Value>) -> Bool {
let lhsCount = lhs.count
if lhsCount != rhs.count {
return false
}
// We know that lhs.count == rhs.count, compare element wise.
for idx in 0..<lhsCount {
if lhs[idx].key != rhs[idx].key ||
lhs[idx].value != rhs[idx].value {
return false
}
}
return true
}
}

extension DictionaryLiteral : Hashable where Key: Hashable, Value : Hashable {
/// The hash value for the dictionary.
///
/// Two dictionaries that are equal will always have equal hash values.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
@_inlineable // FIXME(sil-serialize-all)
public var hashValue: Int {
// FIXME(ABI)#177: <rdar://problem/18915294> Issue applies to DictionaryLiteral too
var result: Int = 0
for element in self {
let elementHashValue = _combineHashValues(element.key.hashValue, element.value.hashValue)
result = _combineHashValues(result, elementHashValue)
}
return result
}
}

extension String {
/// Creates a string representing the given value.
///
Expand Down
9 changes: 9 additions & 0 deletions test/stdlib/DictionaryLiteral.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,12 @@ expectType(DictionaryLiteral<String, NSObject>.self, &hetero1)

var hetero2: DictionaryLiteral = ["a": 1 as NSNumber, "b": "Foo" as NSString]
expectType(DictionaryLiteral<String, NSObject>.self, &hetero2)

let instances: [DictionaryLiteral<Int, String>] = [
[1: "a", 1: "a", 2: "b"],
[1: "a", 2: "b", 1: "a"],
[2: "b", 1: "a", 1: "a"],
[1: "a", 1: "a", 1: "a"]
]
checkEquatable(instances, oracle: { $0 == $1 })
checkHashable(instances, equalityOracle: { $0 == $1 })

0 comments on commit 4692242

Please sign in to comment.