Iree Iree - 2 months ago 5
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
try?
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
let
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

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 bugs.swift.org, 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!)

Comments