Do-try-catch in init -- var versus let

Hi All,


I'm trying to use do-try-catch in an init method that I had formerly designated as a failable initalizer. I think it makes more sense to dispense with the optional return type and rely on exceptions in many cases. My problem, however, is that you're not allowed to have ivars unassigned. Also, you can't re-set the value of immutable ivars (such as default values provided at the class scope) in an init; they have to be declared as var rather than let. I can't think of a way to maintain the immutability of my ivars while also using exceptions to trap errors. Ideas?


Example of a class that doesn't work:

class example {
  let value: Int

  init throws {
    do {
      value = try somethingThatThrows()
    } catch let error {
      throw error
    }
  }
}


Example of a class that is "fixed":

class example {
  var value: Int = 0

  init throws {
    do {
      value = try somethingThatThrows()
    } catch let error {
      throw error
    }
  }
}


Thanks in advance,

- Will

class C {
  let value: Int

  init() throws {
    do {
      let tryvalue = try somethingThatThrows()
      value = tryvalue
    } catch {
      value = 0
      throw error
    }
  } 
}

That certainly works, but it's part of what I'm trying to avoid. I have about 50 initialized variables that I'll have to duplicate in the catch block. It's definitely not a pretty situation.

Do-try-catch in init -- var versus let
 
 
Q