Directory listing using NSFileManager in Swift 2

For some reason, my newbie bones found this a really tricky thing to get working, but there you go.
All I wanted was a function that would list the contents of a directory passed as string. I didn’t manage to get full error-handling working, but the function returns an empty array if it doesn’t come up with anything…

func contentsOfDirectoryAtPath(path: String) -> [String] {
let fm = NSFileManager.defaultManager()
var contents: [String] = []

do {
let items = try fm.contentsOfDirectoryAtPath(path)
for item in items {
} catch {
return []

return contents

let path: String = “/Users/andy/Dropbox”
let files: [String] = contentsOfDirectoryAtPath(path)

if files.count == 0 {
print(“no results”)
else {
for item in files {
print(“item: \(item)”)

NSFileManager seems like a great way to deal with file management issues, but with the implementation changing in Swift 2, and probably due another change when Swift 3 comes out, it appears to be a tricky beast to manage.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s