FileManager extension for PropertyListEncoder. part 2

In my previous post I wrote about adding a convenience method to encode objects using PropertyListEncoder and save it to a given URL using FileManager.

So the only method that was missing was a convenient method to decode saved object from the file.

This is a short post, since decode for PropertyListDecoder is identical to one for JSONDecoder. You can read more about decoding objects here.

Here is the implementation of the method:

public func decodePlist<T: Decodable>(as type: T.Type, using decoder: PropertyListDecoder = PropertyListDecoder(), from url: URL) throws -> T? {
     guard let data = FileManager.default.contents(atPath: url.path) else {
return nil
    return try decoder.decode(type, from: data)

The parameters for the method are:

  1. A type of the object that is being decoded
  2. Decoder with a default set to PropertyListDecoder()
  3. A URL to a file with encoded object.

The method first checks if the file exists, and returns nil if it does not.

If the file exists, contents of the file is passed to decode method of the decoder.

The method will return an object of specified type, or will throw an error if something goes wrong.

Here is a link to a pull request on GitHub and to all files that were changed, including a Unit Test method.