Skip to content

Instantly share code, notes, and snippets.

@AndreyAnt
Created March 12, 2020 08:42
Show Gist options
  • Save AndreyAnt/5c008d481f6a543c56dfd18f2beb2e31 to your computer and use it in GitHub Desktop.
Save AndreyAnt/5c008d481f6a543c56dfd18f2beb2e31 to your computer and use it in GitHub Desktop.
/// Обертка ошибки, позволяющая превратить протоколизированный тип, в конкретный
private struct DecodableErrorWrapper: Decodable {
// Статический ключ по которому будем передавать тип
fileprivate static let typeKey = CodingUserInfoKey(rawValue: "decodableErrorType")!
// Ошибка реализующая протокол, но без конкретного типа
fileprivate let error: DecodableError
// Кастомный декодер инициализатор
init(from decoder: Decoder) throws {
// Вытаскиваем тип ошибки и кастим его в DecodableError
guard let errorType: DecodableError.Type = decoder.userInfo[DecodableErrorWrapper.typeKey] as? DecodableError.Type else {
let description = "Concrete type of DecodableError cannot be recieved from decoder.userInfo. Please check that you are injecting your error type with the correct key"
let context = DecodingError.Context(codingPath: [], debugDescription: description)
throw DecodingError.dataCorrupted(context)
}
// Инициализируем ошибку уже с определенным типом, но хранящуюся как протокол
self.error = try errorType.init(from: decoder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment