What is the difference when calling url(forResource:withExtension:) with an extension and without it?

The method url(forResource:withExtension:) can be called like this:

let url = Bundle.module.url(forResource: "foo", withExtension: "txt")!

or like this:

let url = Bundle.module.url(forResource: "foo.txt", withExtension: nil)!

Both ways seems to work.

Are there any differences between the two?

Answered by DTS Engineer in 765551022

Not really. Well, more accurately, not on current systems. Foundation was designed to be portable, and not all systems embed the file type into the name in the way that you expect if you come from a Unix-y background.

This is the same reason that Foundation has methods like URL.appendingPathExtension(_:) where you could otherwise achieve the same result by string concatenation.

Is your code likely to be ported to a platform that needs this? Probably not. But it still makes sense to pass the right values to the right parameters.

Oh, and one place where this really makes sense is when you want to get all resources of the same type, using a routine like urls(forResourcesWithExtension:subdirectory:).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Not really. Well, more accurately, not on current systems. Foundation was designed to be portable, and not all systems embed the file type into the name in the way that you expect if you come from a Unix-y background.

This is the same reason that Foundation has methods like URL.appendingPathExtension(_:) where you could otherwise achieve the same result by string concatenation.

Is your code likely to be ported to a platform that needs this? Probably not. But it still makes sense to pass the right values to the right parameters.

Oh, and one place where this really makes sense is when you want to get all resources of the same type, using a routine like urls(forResourcesWithExtension:subdirectory:).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

What is the difference when calling url(forResource:withExtension:) with an extension and without it?
 
 
Q