[swift-evolution] Remove Failable Initializers

Thorsten Seitz tseitz42 at icloud.com
Sat Mar 5 09:54:50 CST 2016


+1 to everything Brent said.

-Thorsten 

Am 03.03.2016 um 10:20 schrieb Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org>:

>> 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
> Architechies
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


More information about the swift-evolution mailing list