Uploaded image for project: 'Swift'
  1. Swift
  2. SR-10464

Optional URL value with Decodable protocol failing

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:
    • Environment:

      Swift 4.2
      Xcode 10.1 (10B61)

      Description

      struct MyStruct: Decodable {
          let id: String
          let homepageUrl: URL?
      
          //    private enum CodingKeys: String, CodingKey {
          //        case id, homepageUrl = "homepage_url"
          //    }
      }
      
      let dict = [
          "id": "1",
          "homepage_url": ""
      ]
      
      let decoder = JSONDecoder()
      decoder.keyDecodingStrategy = .convertFromSnakeCase
      
      let data = try JSONSerialization.data(withJSONObject: dict)
      let myStruct = try decoder.decode(MyStruct.self, from: data)
      print("m: \(myStruct.id) - \(String(describing: myStruct.homepageUrl))")
      

      In this case the error message is `Invalid URL string.` which is correct because it's an empty string so its not a valid URL, but the `homepageUrl` is optional, so it should produce a nil value instead of failing.

      If the `MyStruct` is using `CodingKeys` (uncomment that part of the code), then its working fine with empty string in dictionary.

      I think its a swift bug because: If `keyDecodingStrategy` is `convertFromSnakeCase` then it should produce nil without using `CodingKeys`.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              szuniverse Szurma David
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated: