Iree Iree - 1 year ago 44
Swift Question

Use the try? operator to make the code more concise

I have this code in Swift 2 to move a file to a new destination, overwriting if necessary:

let origin = "...", destination = "..."
do {
try NSFileManager.defaultManager().removeItemAtPath(destination) // remove existing file
} catch {}
do {
try NSFileManager.defaultManager().moveItemAtPath(origin, toPath: destination)
} catch {}

To make the code more concise, and since I don't care about the error thrown, I thought of using the
operator as follows:

let origin = "...", destination = "..."
try? NSFileManager.defaultManager().removeItemAtPath(destination)
try? NSFileManager.defaultManager().moveItemAtPath(origin, toPath: destination)

This creates a compiler warning that the result of the operation is being unused, so I have to add an unused
and it looks awful:

let _ = try? NSFileManager.defaultManager().moveItemAtPath(origin, toPath: destination)

Is it bad to let the warnings there in the sake of conciseness?

Answer Source

In Swift 3 it is legal to ignore the result without the extra assignment. This compiles just fine in the Xcode 8 GM:

try? FileManager.default.removeItem(atPath: destination)

(Earlier, by the way, I asked about this on, and was told directly that this _ = try? syntax is regarded as correct and is a small price to pay for acknowledging to the compiler — and yourself — that you are deliberately ignoring the returned value. So what you are doing is just fine while you remain in the Swift 2 world!)