如何检查 fileURL(withPath:) 的 return 值是否失败?

How to check return value of fileURL(withPath:) for failure?

我正在将一些 Objective-C 代码转换为 Swift。 Objective-C 看起来像:

NSURL *urlPathForScans = [NSURL fileURLWithPath:sDirIn];
if (nil != urlPathForScans) { 
    // some code…

我已经将该代码转换为:

var urlPathForScans = NSURL.fileURL(withPath: sDirIn)
if urlPathForScans != nil  {
    // some code …

这在我构建时给了我以下警告:

Comparing non-optional value of type 'URL' to 'nil' always returns true

NSURL.fileURL(withPath:) 的 Swift 文档没有以任何方式暗示 return 值可能表示失败,即使提供的路径参数显然可能无效。如果 sDirIn 不是有效路径,如何在此处正确检查 return 值是否失败?

似乎这种方法永远不会失败。 Objective-C 代码中的检查是多余的。稍后尝试通过此 url.

获取文件时,您将需要对 nil 执行检查

In Swift fileURLWithPath returns 一个非可选的不能是 nil

并且请使用原生 URL 而不是 NSURL

let urlPathForScans = URL(fileURLWithPath: sDirIn)

您可以检查 URL 是否有效

if FileManager.default.fileExists(atPath: sDirIn) {

}

let urlIsValid = (try? urlPathForScans.checkResourceIsReachable()) ?? false