Last active
April 24, 2021 18:57
-
-
Save bocato/673a27c695f5543d02d5cb5629b56187 to your computer and use it in GitHub Desktop.
testing_fatal_errors_2.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public struct AnyEquatable: Equatable { | |
// MARK: - Properties | |
public let erasedValue: Any | |
private let isEqual: (AnyEquatable) -> Bool | |
private let failureHandler: (_ message: @autoclosure () -> String, StaticString, UInt) -> Never | |
// MARK: - Initialization | |
public init<S>( | |
id: String = UUID().uuidString, | |
erasing value: S | |
) where S: Equatable { | |
self.init( | |
erasing: value, | |
failureHandler: Swift.fatalError(_:file:line:) | |
) | |
} | |
init<S>( | |
erasing value: S, | |
failureHandler: @escaping (_ message: @autoclosure () -> String, StaticString, UInt) -> Never | |
) where S: Equatable { | |
erasedValue = value | |
isEqual = { otherAnyEquatable in | |
guard let other = otherAnyEquatable.erasedValue as? S else { return false } | |
return other == value | |
} | |
self.failureHandler = failureHandler | |
} | |
// 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) | |
failureHandler("Trying to cast \(expectedType) to \(typePassed)!", #file, #line) | |
} | |
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