FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

SOLVED: Hacking with macOS, Project 7, do...try...catch

Forums > macOS

So, in the drag and drop section of Project 7, we create a method performExternalDrag to copy pictures into the application's data folder and then insert the pictures into the grid. The copy might not work for a variety of reasons, so we wrap the copy instruction with do { try <attempt to copy> } catch { <print an error to the console> } but then after this we go ahead and insert the item into the grid.

Now, I'm new to Swift (which is why I'm reading this course), so maybe (probably) my understanding of its exception handling is flawed, but shouldn't that insertion only get executed if the copy succeeds? Won't the presented implementation fail unpleasantly if the copy doesn't work?

   

Yep, you're right about it going weird. In fact, you can test it by defining an error enum, something like enum TestError: Error { case foo } and then throwing it before trying to copy the file:

do {
    throw TestError.foo
    try fm.copyItem(at: sourceURL, to: destinationURL)
} catch {
    ...
}

This forces an exception instead of the copy, and you can test out the behaviour. I solved the issue just by adding a continue statement at the end of the catch block, which skips the insertion of the items when the copying fails, and it fixed the issue.

do {
    try fm.copyItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error copying item from: \(sourceURL): \(error)")
    continue
}

--Jakub

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.