[swift-evolution] Remove Failable Initializers

Brent Royal-Gordon brent at architechies.com
Thu Mar 3 03:20:13 CST 2016

> class Model {
> let property: String
> let property1: String
> let property2: String
> let property3: String
> init?(json: [String: AnyObject]) throws {
> property = try json.require("property")
> property1 = try json.require("property1")
> property2 = try json.require("property2")
> property3 = try json.require("property3")
> }
> }
> Require reads the key from the dict and tries to cast it to the same type as the variable its being assigned to and throws an error if this fails (like it doesn't exist or it can't be casted). This has much less boilerplate, its easier to read and also we can throw an error saying ("We couldn't parse property1"). 

You're right, that's an improvement over the failable initializer. *So make this a throwing init instead.* It's not like the existence of failable initializers keeps you from using `throws`.

Meanwhile, things like `Int.init(_: String)` and `NSImage.init(data: NSData)` are better off being failable. There's not much useful detail you can provide for these failures, and it's really nice to be able to use if-let, guard-let, or ?? to handle them instead of having to write an entire do/catch block.

It's helpful to have both a hammer *and* a screwdriver in your toolkit, lest you be forced to treat everything like a nail.

Brent Royal-Gordon

More information about the swift-evolution mailing list