[swift-evolution] Idea: Properties in Failable Initializers less verbose

Chris Lattner clattner at nondot.org
Wed Jul 26 11:13:04 CDT 2017


> On Jul 25, 2017, at 2:44 AM, philohan95 via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think the current way to initiate models in a Failable Initializer `init?()` is overly verbose and should be shortened down so less boilerplate should be needed.
> 
> The current way:
> 
> ```
> let someProperty: Any
> let anotherProperty: Any
> 
> init?(data: [String: Any]) {
> 	guard
> 		let someProperty = data["some_key"],
> 		let anotherProperty = data["another_key"]
> 	else {
> 		return nil
> 	}
> 
> 	self. someProperty = someProperty
> 	self. anotherProperty = anotherProperty
> }
> ```

Guard isn’t really the right answer for this, I’d try something like this (where unwrapOrThrow is the obvious generic function you can define yourself):

init?(data: [String: Any]) {
	do {
		self.someProperty = try unwrapOrThrow(data["some_key”])
		self.anotherProperty = try unwrapOrThrow(data["another_key”])
	} catch {
		return nil
	}
}

-Chris



More information about the swift-evolution mailing list