Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ludwig/7724f4ff9d57c5c40552 to your computer and use it in GitHub Desktop.
Save ludwig/7724f4ff9d57c5c40552 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", ... ]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment