UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on 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?

3      

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

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.