Get Folder's Number of Elements

How can I get element number of a folder as a value for label?

FileManager is what you want.

import Foundation
let path = "/"
let numberOfItems = try FileManager.default.contentsOfDirectory(atPath: path).count


contentsOfDirectory(atPath:) will work but my general advice is that you use the URL based API for working with the file system. Specifically, to enumerate a directory use contentsOfDirectory(at:includingPropertiesForKeys:options:). That has the advantage that the returned URL values have cached the properties you request. For example, if only want to count visible items in the directory, you’d need to fetch the .isHiddenKey property for each item, and doing that as part of the enumeration is much faster than doing it one item at a time.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple


@eskimo @Diggory thank you so much for information! I achieved what I want!

I wish this information was part of the docs, instead of part of the lore.

Neither the docs on the web, nor the header comments mention this (which by the way are two different sets of text).


The "deprecation" of paths in favor of URLs? Yes, that's a topic that imho would benefit from some cleanup - ideally, there would also be a separate type for local URLs (Swift itself doesn't offer much to work with files, does it? It's all inherited from Foundation).

Terms of Service

Privacy Policy

Cookie Policy