An elegant way to ignore any errors thrown by a method An elegant way to ignore any errors thrown by a method swift swift

An elegant way to ignore any errors thrown by a method


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 inthe particular error which was thrown then you can test thereturn 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.defaulttry? fm.removeItem(at: fileURL)

compiles without warnings.