Skip to content

[stdlib] Add conditional Hashable conformance to optional #15579

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions stdlib/public/core/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,30 @@ extension Optional : Equatable where Wrapped : Equatable {
}
}

extension Optional: Hashable where Wrapped: Hashable {
/// The hash value for the optional instance.
///
/// Two optionals 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 {
return _hashValue(for: self)
}

@_inlineable // FIXME(sil-serialize-all)
public func _hash(into hasher: inout _Hasher) {
switch self {
case .none:
hasher.append(0 as UInt8)
case .some(let wrapped):
hasher.append(1 as UInt8)
hasher.append(wrapped)
}
}
}

// Enable pattern matching against the nil literal, even if the element type
// isn't equatable.
@_fixed_layout
Expand Down
13 changes: 13 additions & 0 deletions test/stdlib/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,19 @@ OptionalTests.test("Equatable") {
expectEqual([false, true, true, true, true, false], testRelation(!=))
}

OptionalTests.test("Hashable") {
let o1: Optional<Int> = .some(1010)
let o2: Optional<Int> = .some(2020)
let o3: Optional<Int> = .none
checkHashable([o1, o2, o3], equalityOracle: { $0 == $1 })

let oo1: Optional<Optional<Int>> = .some(.some(1010))
let oo2: Optional<Optional<Int>> = .some(.some(2010))
let oo3: Optional<Optional<Int>> = .some(.none)
let oo4: Optional<Optional<Int>> = .none
checkHashable([oo1, oo2, oo3, oo4], equalityOracle: { $0 == $1 })
}

OptionalTests.test("CustomReflectable") {
// Test with a non-refcountable type.
do {
Expand Down