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

philohan95 iosdev95 at gmail.com
Tue Jul 25 04:43:52 CDT 2017


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
}
```

As you can see we had to use the properties twice (this would also be the case of `if let`) making the initializer twice as long as necessary and becomes a pain to implement when having more than 1 property.

My idea is extending the power of the `guard` statement

Idea:
	init?(data: [String: Any]) {
		guard
			someProperty = data["some_key"], // Currently fails because `self` us used before all stored properties are initialized
			anotherProperty = data["another_key"]
		else {
			return nil
		}
	}
}



More information about the swift-evolution mailing list