I'm trying to figure out why using Optional URLs causes my JSON Decoding to fail using Swift 4. I've already poured over the WWDC "Whats new in Foundation" video, Apples Playground examples, and a bunch of places on the internet but haven't found a solution.
This is a test I created to show the issue. Say this is my json data:
let json = """
{
"kind" : "",
"total" : 2,
"image_url" : "https://www.myawesomeimageURL.com/awesomeImage.jpg"
}
""".data(using: .utf8)!
And this is my struct:
struct BusinessService: Decodable {
let kind: String?
let total: Int
let image_url : URL?
}
And here's where I serialize it:
let myBusiness = try? JSONDecoder().decode(BusinessService.self, from: json)
print(myBusiness)
Now, the problem is if I receive json data where image_url is missing, the json decoding fails and gives me nil.
I am confused as to why "kind" can be an optional string and not cause the json decoding to fail when it has no value, yet image_url cannot be an optional URL without causing the json to fail.
I've been trying to figure this out for two days now with no luck. Does anyone have any insight into why this would fail?
I did notice one more piece of the puzzle, and that is the image_url in the json actually doesn't have to be a valid image URL. I can type in any string and my struct gets serialized so I think maybe I'm misunderstanding how this works. I thought that URL would automatically be populated only if it could convert to a valid URL and that isn't happening.
Any insight to this would be greatly appreciated.