Skip to content

Instantly share code, notes, and snippets.

@bocato
Last active April 24, 2021 18:57
Show Gist options
  • Save bocato/fbe0fc14db68906f6e4998f56ac94b9c to your computer and use it in GitHub Desktop.
Save bocato/fbe0fc14db68906f6e4998f56ac94b9c to your computer and use it in GitHub Desktop.
testing_fatal_errors_1
import Foundation
public struct AnyEquatable: Equatable {
// MARK: - Properties
public let erasedValue: Any
private let isEqual: (AnyEquatable) -> Bool
// MARK: - Initialization
public init<S>(
id: String = UUID().uuidString,
erasing value: S
) where S: Equatable {
erasedValue = value
isEqual = { otherAnyEquatable in
guard let other = otherAnyEquatable.erasedValue as? S else { return false }
return other == value
}
}
// MARK: - Public API
public func unwrapped<S>() -> S? {
erasedValue as? S
}
public func unsafelyUnwrapped<S>() -> S {
guard let unwrapped: S = unwrapped() else {
let expectedType = String(describing: erasedValue)
let typePassed = String(describing: S.self)
fatalError("Trying to cast \(expectedType) to \(typePassed)!")
}
return unwrapped
}
public static func == (lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
lhs.isEqual(rhs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment