0

I'm writing some Swift code to parse filenames of video files and extract the show, season and episode. These are returned as key/value parts in a dictionary. As part of my unit tests, I found something odd. First the code (comments and whitespace removed):

public static func parse(_ filename: String, defaults: [String: String] = [String: String]()) -> [String: String] {
    let url = URL(fileURLWithPath: filename)
    let file = url.deletingPathExtension().lastPathComponent
    if file.count == 0 {
        return ret
    }
    if file.count > 0 {
        ret["file"] = file
    }
    let ext = url.pathExtension
    if ext.count > 0 {
        ret["extension"] = ext
    }
    let path = url.deletingLastPathComponent().path
    if path.count > 0 {
        ret["path"] = path
    }

I called this in my test case thus...

ParseVideoFilename.parse("non-empty-filename.m4v")

And this is what resulted:

["ext": "m4v", "file": "non-empty-filename", "path": "/private/tmp"]

I am a bit surprised about that path. I did not pass that in, so I assume URL is doing something here. I don't expand the path nor resolve it. Is this expected behavior, and if so, why?

Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98

1 Answers1

1

Running your code in a playground just gave me file:///private/var/folders/1p/wpwdypm96_s5zfwxxzvwwp0m0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.Playground-C18F0418-5C1D-4772-9AE9-E3EF9AA2F07C/non-empty-filename.m4v as the output of

let url = URL(fileURLWithPath: filename)
print(url.absoluteString)

This looks to me as the current directory of the process that gets executed by Playground. I'm not at all surprised by this, since we gave URL a relative path without any base and the file URI scheme doesn't really know how to handle relative paths (see e.g. this answer)

If you absolutely don't want to see these artifacts, you can modify your parser to use an absolute path:

let url = URL(fileURLWithPath: "/" + filename)
print(url.absoluteString) // prints "file:///non-empty-filename.m4v"
Gereon
  • 17,258
  • 4
  • 42
  • 73