Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active December 13, 2016 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/73c19aaed3792723ba3e8c28960d94e2 to your computer and use it in GitHub Desktop.
Save robertmryan/73c19aaed3792723ba3e8c28960d94e2 to your computer and use it in GitHub Desktop.
func open(_ filePath: String) throws -> NSArray {
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
let object: Any?
if #available(OSX 10.11, *) {
object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as NSData)
} else {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
object = unarchiver.decodeObject(forKey: "root")
}
guard let unarchivedObject = object else {
throw ArchiveError.unableToUnarchive
}
guard let array = unarchivedObject as? NSArray else {
throw ArchiveError.notArray
}
return array
}
enum ArchiveError: Error {
case unableToUnarchive
case notArray
}
@robertmryan
Copy link
Author

In further refinement, I'd (a) not have try in the name of the method; and (b) retire use of NSException (we're throwing errors, not exceptions).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment