Last active
June 12, 2017 15:08
-
-
Save ken0nek/4a84f5fb1d13e4201907ddcdcccc3cf1 to your computer and use it in GitHub Desktop.
Can not decode an entity which has Optional<URL> property.
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
//: Playground - noun: a place where people can play | |
import UIKit | |
struct URLCodableTest: Codable { | |
let ou: URL? | |
let u: URL | |
enum CodingKeys: String, CodingKey { | |
case ou | |
case u | |
} | |
init(ou: URL? = URL(string: "https://www.apple.com"), u: URL = URL(string: "https://www.apple.com")!) { | |
self.ou = ou | |
self.u = u | |
} | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
self.ou = try values.decodeIfPresent(URL.self, forKey: .ou) | |
self.u = try values.decode(URL.self, forKey: .u) | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: CodingKeys.self) | |
try container.encode(ou, forKey: .ou) | |
try container.encode(u, forKey: .u) | |
} | |
} | |
let t = URLCodableTest() | |
do { | |
let d = try JSONEncoder().encode(t) | |
print(d) | |
let j = try? JSONSerialization.jsonObject(with: d, options: .allowFragments) | |
print(j) | |
/* | |
Optional({ | |
ou = { | |
relative = "https://www.apple.com"; | |
}; | |
u = "https://www.apple.com"; | |
}) | |
*/ | |
do { | |
let tt = try JSONDecoder().decode(URLCodableTest.self, from: d) | |
print(tt) | |
} catch let e as DecodingError { | |
switch e { | |
case let .dataCorrupted(c): | |
print(c) | |
case let .keyNotFound(k, c): | |
print(k, c) | |
case let .typeMismatch(t, c): | |
print(t, c.debugDescription) | |
// -> String Expected to decode String but found a dictionary instead. | |
case let .valueNotFound(t, c): | |
print(t, c) | |
} | |
} catch let e { | |
print(e.localizedDescription) | |
} | |
} catch let e as EncodingError { | |
switch e { | |
case let .invalidValue(v, c): | |
print(v, c) | |
} | |
} catch let e { | |
print(e.localizedDescription) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment