[swift-evolution] Why does URL.checkResourceIsReachable() return a Bool?

Charles Srstka cocoadev at charlessoft.com
Mon Aug 8 17:13:41 CDT 2016


> On Aug 8, 2016, at 4:32 PM, Kevin Ballard <kevin at sb.org> wrote:
> 
> The documentation is wrong (for Swift).
> 
> For file URLs, this method returns true/false without throwing an error (at least, if the file doesn't exist there's no error; I don't know if there are conditions that would cause an error to be returned).
> 
> For non-file URLs this method throws an error.
> 
> The bit about "For other URL types, false is returned" is written for Obj-C, where you can completely disregard the error. You can't disregard the error in Swift, so it doesn't apply (though you can use try? and treat a nil value the same as false)

In my testing, this does not appear to be correct; it actually seems to throw an error in both cases. For a file URL pointing to a file that doesn’t exist, it throws NSFileReadNoSuchFileError, and for an HTTP URL, it throws NSFileNoSuchFileError. This further causes me to question the purpose of having the method return a boolean.

Here’s the code:

import Foundation

let fileURL = URL(fileURLWithPath: "/asdfasdfasdf")
let httpURL = URL(string: "http://asdfasdfasdf.com/asdfasdfasdf")!

do {
    if try fileURL.checkResourceIsReachable() {
        print("file URL is reachable")
    } else {
        print("file URL returned false")
    }
} catch {
    print("file URL threw error: \(error)")
}

do {
    if try httpURL.checkResourceIsReachable() {
        print("http URL is reachable")
    } else {
        print("http URL returned false")
    }
} catch {
    print("http URL threw error: \(error)")
}


And the output:

file URL threw error: Error Domain=NSCocoaErrorDomain Code=260 "The file “asdfasdfasdf” couldn’t be opened because there is no such file." UserInfo={NSURL=file:///asdfasdfasdf, NSFilePath=/asdfasdfasdf, NSUnderlyingError=0x100903eb0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
http URL threw error: Error Domain=NSCocoaErrorDomain Code=4 "The file doesn’t exist."
Program ended with exit code: 0

Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160808/9df28b39/attachment.html>


More information about the swift-evolution mailing list