Created
March 12, 2020 08:42
-
-
Save AndreyAnt/5c008d481f6a543c56dfd18f2beb2e31 to your computer and use it in GitHub Desktop.
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
/// Обертка ошибки, позволяющая превратить протоколизированный тип, в конкретный | |
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