You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let encodable = [NSError(domain: "domain", code: 100, userInfo: nil)]
try? JSONEncoder().encode(encodable)
we see that, unlike the promised throw, execution halts with a fatal error.
This is contrary to desirable function, in that there is no way to determine whether, for example, an Array (which claims conformance with Encodable and therefore can't be skipped via a guard) will successfully encode or simply crash.
Ideally, this is exactly the purpose of try, which should allow us to get a result or not if none can be had.
The text was updated successfully, but these errors were encountered:
In Swift 4.1, Array is now only Encodable if its elements are Encodable. Even without that, though, precondition is the correct behavior. The programmer should know what they are trying to encode, and it is a programmer error if they try to encode something that isn't Encodable. Error and try are only meant for things that are out of the programmer's control, like disk or network access or parsing user input.
What do you suggest is the ideal pattern is for the case of writing tests against bad input? These can no longer be written to confirm that an array is not encoded (as expected). Does the compile-time check remove the need for such tests?
Additional Detail from JIRA
md5: f7b9e8bd44203880dbd6c4d0b051578e
Issue Description:
Docs for JSONEncoder.encode() state:
Yet the actual implementation appears to do something more like
https://gist.github.com/mishagray/3ee82a3a82f357bfbf8ff3b3d9eca5cd#file-realmswift-codable-swift-L19
i.e., a preconditionFailure.
Testing the following in a playground
let encodable = [NSError(domain: "domain", code: 100, userInfo: nil)]
try? JSONEncoder().encode(encodable)
we see that, unlike the promised throw, execution halts with a fatal error.
This is contrary to desirable function, in that there is no way to determine whether, for example, an Array (which claims conformance with Encodable and therefore can't be skipped via a guard) will successfully encode or simply crash.
Ideally, this is exactly the purpose of try, which should allow us to get a result or not if none can be had.
The text was updated successfully, but these errors were encountered: