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

Decodable does not fail to decode Float as Int for whole numbers

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: In Progress
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:

      Description

      Decodable should cause run time errors when attempting to parse Floats as Integers. However, this does not occur when the Float value is a whole number. Because Decodable will only fail at runtime, it is prudent that it correctly fails on these simpler cases as it can mask issues

      import Foundation
      
      struct Swifter: Decodable {
        let floatParsedAsInt: Int
      }
      
      let json = """
      {
       "floatParsedAsInt": 1.0,
      }
      """.data(using: .utf8)!
      let myStruct = try JSONDecoder().decode(Swifter.self, from: json)
      print(myStruct.floatParsedAsInt) //output 1
      

       By comparison the swift compiler would reject the follow code:

      var intValue: Int = 1.0 // Error: cannot convert value of type 'Double' to specified type 'Int'
      

      or

      
      struct JSONStructureWithInt: Decodable {
        let intAsString: Int
      }
      
      let json = """
      {
       "intAsString": "1",
      }
      """.data(using: .utf8)!
      
      let myStruct1 = try JSONDecoder().decode(JSONStructureWithString.self, from: json) // Error: Expected to decode Int but found a string/data instead
      print(myStruct1.intAsString) 
      

        Attachments

          Activity

            People

            • Assignee:
              hungtruong Hung Truong
              Reporter:
              jozen Julian
            • Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

              Dates

              • Created:
                Updated: