Handle decoding nil for optional T types in Failable

This commit is contained in:
Caleb Kleveter 2019-01-23 10:11:08 -06:00
parent a11244d687
commit 3520d9a9bb
No known key found for this signature in database
GPG Key ID: B38DBD5CF2C98D69
1 changed files with 12 additions and 1 deletions

View File

@ -12,6 +12,17 @@ extension Failable: Decodable where T: Decodable {
/// See [`Decodable.init(from:)`](https://developer.apple.com/documentation/swift/decodable/2894081-init)
public init(from decoder: Decoder)throws {
let container = try decoder.singleValueContainer()
try self.init(container.decode(T.self))
guard _isOptional(T.self) else {
try self.init(try container.decode(T.self))
return
}
guard container.decodeNil() else {
try self.init(try container.decode(T.self))
return
}
try self.init(Void?.none as! T)
}
}