FileManager extension for PropertyListEncoder. part 2

Alexei Kozachenko
Dec 9, 2018 · 1 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store