EquatableError.swift (2198B)
1 // MIT License 2 // Copyright © Thibault Wittemberg thibault@sideeffect.io 3 // https://sideeffect.io/posts/2021-12-10-equatableerror/ 4 // 5 // Permission is hereby granted, free of charge, to any person obtaining a copy of this software 6 // and associated documentation files (the "Software"), to deal in the Software without restriction, 7 // including without limitation the rights to use, copy, modify, merge, publish, distribute, 8 // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 9 // furnished to do so, subject to the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included in all copies or 12 // substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 15 // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 16 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 17 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 // 20 21 struct EquatableError: Error, Equatable, CustomStringConvertible { 22 let base: Error 23 private let equals: (Error) -> Bool 24 25 init<Base: Error>(_ base: Base) { 26 self.base = base 27 self.equals = { String(reflecting: $0) == String(reflecting: base) } 28 } 29 30 init<Base: Error & Equatable>(_ base: Base) { 31 self.base = base 32 self.equals = { ($0 as? Base) == base } 33 } 34 35 static func ==(lhs: EquatableError, rhs: EquatableError) -> Bool { 36 lhs.equals(rhs.base) 37 } 38 39 var description: String { 40 "\(self.base)" 41 } 42 43 func asError<Base: Error>(type: Base.Type) -> Base? { 44 self.base as? Base 45 } 46 47 var localizedDescription: String { 48 self.base.localizedDescription 49 } 50 } 51 52 extension Error where Self: Equatable { 53 func toEquatableError() -> EquatableError { 54 EquatableError(self) 55 } 56 } 57 58 extension Error { 59 func toEquatableError() -> EquatableError { 60 EquatableError(self) 61 } 62 }