Which doesn’t actually work because you can’t make a URL with a
relative path like that (I wanted it to be relative to the current
Hmmm. Either I’m radically misunderstanding your requirements or you’re really off in the weeds.
URL fully supports relative URLs, and that includes current-working-directory-relative file URLs constructed from relative file paths. Your code works as is:
$ cat makerom.swift
let rom = [UInt8](repeating: 0xea, count: 32768)
try Data(rom).write(to: URL(fileURLWithPath: "rom.bin"))
catch let e
print("Error writing rom.bin: \(e)")
$ chmod +x makerom.swift
$ ls -l rom.bin
-rw-r--r-- 1 quinn staff 32768 5 Nov 08:54 rom.bin
Now, just to make sure it’s not relative to the script, let’s change directories:
$ mkdir tmp
$ cd tmp
$ ls -l rom.bin
-rw-r--r-- 1 quinn staff 32768 5 Nov 08:55 rom.bin
This is on macOS 10.14.6 with Xcode 11.2, but it should behave the same in any version of Swift.
If you want to construct a file URL that’s explicitly relative to some directory (rather than the current working directory), you can use
One thing to watch out for here is that relative URLs ‘latch’ the current working directory in their
baseURL property, so if you change working directory the URL will remain relative to the original one:
let u1 = URL(fileURLWithPath: "rom.bin")
print(u1.absoluteURL) // prints "file:///Users/quinn/rom.bin"
print(u1.absoluteURL) // still prints "file:///Users/quinn/rom.bin"
let u2 = URL(fileURLWithPath: "rom.bin")
print(u2.absoluteURL) // prints "file:///Library/rom.bin"
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple