Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active November 15, 2017 18:11
Show Gist options
  • Select an option

  • Save kristopherjohnson/dc733dfa3d55df6cc612 to your computer and use it in GitHub Desktop.

Select an option

Save kristopherjohnson/dc733dfa3d55df6cc612 to your computer and use it in GitHub Desktop.
Using NSFileManager contentsOfDirectoryAtPath in Swift, with tuple result and CPS interfaces
import Foundation
// Tuple result
// Get contents of directory at specified path, returning (filenames, nil) or (nil, error)
func contentsOfDirectoryAtPath(path: String) -> (filenames: String[]?, error: NSError?) {
var error: NSError? = nil
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath(path, error: &error)
if contents == nil {
return (nil, error)
}
else {
let filenames = contents as String[]
return (filenames, nil)
}
}
let (filenamesOpt, errorOpt) = contentsOfDirectoryAtPath("/Users")
if let filenames = filenamesOpt {
filenames // [".localized", "kris", ...]
}
let (filenamesOpt2, errorOpt2) = contentsOfDirectoryAtPath("/NoSuchDirectory")
if let err = errorOpt2 {
err.description // "Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. ... "
}
// Continuation Passing Style (CPS) interface
// Get contents of directory at specified path, invoking block with (filenames, nil) or (nil, error)
func getContentsOfDirectoryAtPath(path: String, block: (filenames: String[]?, error: NSError?) -> ()) {
var error: NSError? = nil
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath(path, error: &error)
if contents == nil {
block(filenames: nil, error: error)
}
else {
let filenames = contents as String[]
block(filenames: filenames, error: nil)
}
}
getContentsOfDirectoryAtPath("/Users") { (result, error) in
if let e = error {
e.description
}
else if let filenames = result {
filenames // [".localized", "kdj", ... ]
}
}
getContentsOfDirectoryAtPath("/NoSuchDirectory") { (result, error) in
if let e = error {
e.description // "Error Domain=NSCocoaError..."
}
else if let filenames = result {
filenames
}
}
// Do something with the files in my home directory
let listMyFiles = { block in getContentsOfDirectoryAtPath("/Users/kdj", block) }
listMyFiles { (result, error) in
if let e = error {
e.description
}
else if let filenames = result {
filenames // [".bashrc", ... ]
}
}
@kergunyahite
Copy link
Copy Markdown

OK. Did not work in a Playground but fine in a project.
Is there any info on PlayGround limitations?

@olivier38070
Copy link
Copy Markdown

doesn't compile at all in swift 3. 21 error...

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