0

I want to do something like

doc = try? Doc(url) else Doc()

Is there a way to do something clean like that without much ado? I tried

doc = try? Doc(url) : Doc()

But that didn't work

  • 7
    you can use nil coalescing operator `doc = (try? Doc(url)) ?? Doc()` – Leo Dabus Jan 11 '22 at 18:59
  • 1
    Possibly helpful: https://stackoverflow.com/q/57568204/1187415. – Martin R Jan 11 '22 at 19:33
  • If you do this often, create yourself an extension: `extension Doc { convenience init(maybeUrl url: URL) { do { try self.init(url) } catch { self.init() }}}` and then do `doc = Doc(maybeUrl: url)` – timbre timbre Jan 11 '22 at 21:14
  • Does this answer your question? [Using nil-coalescing operator with try? for function that throws and returns optional](https://stackoverflow.com/questions/57568204/using-nil-coalescing-operator-with-try-for-function-that-throws-and-returns-opt) – muhasturk Jan 12 '22 at 12:18

0 Answers0