Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

ios - An elegant way to ignore any errors thrown by a method

I'm removing a temporary file with NSFileManager like this:

let fm = NSFileManager()
fm.removeItemAtURL(fileURL)
// error: "Call can throw but it is not marked with 'try'"

I don't really care if the file is there when the call is made and if it's already removed, so be it.

What would be an elegant way to tell Swift to ignore any thrown errors, without using do/catch?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't care about success or not then you can call

let fm = NSFileManager.defaultManager()
_ = try? fm.removeItemAtURL(fileURL)

From "Error Handling" in the Swift documentation:

You use try? to handle an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil.

The removeItemAtURL() returns "nothing" (aka Void), therefore the return value of the try? expression is Optional<Void>. Assigning this return value to _ avoids a "result of 'try?' is unused" warning.

If you are only interested in the outcome of the call but not in the particular error which was thrown then you can test the return value of try? against nil:

if (try? fm.removeItemAtURL(fileURL)) == nil {
    print("failed")
}

Update: As of Swift 3 (Xcode 8), you don't need the dummy assignment, at least not in this particular case:

let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)

compiles without warnings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...