> On Aug 8, 2016, at 4:32 PM, Kevin Ballard <[email protected]> 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
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to