Is it safe to assume caches directory in the user domain always exist on iOS

On iOS 16 we can use URL.cachesDirectory to get a non optional URL to the cache files directory for the current user.

Pre iOS 16 we would need to do something like:

let url = FileManager.default.urls(
  for: .cachesDirectory, 
  in: .userDomainMask
)[0] // <- Is this safe?

My assumption has always been that that is safe on iOS. i.e. There will be at least 1 URL returned from NSFileManager.urls(for:in:).

But recently I've started working on a project which doesn't make that assumption. I cannot find this documented anywhere so thought here would be the best place to ask.

Thank you!

This is not exactly about Swift.


It's probably premature "what if" thinking on their behalf. I'd make this assumption that's there's exactly one cache directory (via precondition(folders.count == 1)). Once this crashes (if ever!) I'd be among the first ones to know the actual truth :slight_smile:

1 Like