[swift-evolution] Failable Initializer Suggestion

Manfred Lau wezzardlau at gmail.com
Sun Dec 27 07:22:39 CST 2015


Hello.

I just found that the design of failable initializer is redundant in Swift 2. Because native error handling already has been introduced in Swift 2, and failable initializer indeed could be achieved by following codes:

	class AClass {
		init() throws {
			// initialize and throw error when failed
		}
	}

	let anInstance = try? AClass()

And you can get the reason why the initialization was failed to guide your following recovering by using codes below, which is not able to be done with failable initializer:

	do { 
		let anInstance = try AClass()
	} catch let error {
		// recover from the error
	}

Probably the heaviest impact to current code done by removing failable initializer is the consequential changes of NSCoding protocol’s designated initializer.

As NSCoding protocol defines a designated initializer which unarchives the object graph from the archived data which could be invalid (by a wrong treating during a previous encoding), expired (by a software upgrade) or corrupted (by a disk error or user corrupting), the initialization might be failed respectively. But according the Objective-C’s design, such a failure is implicit and no error info would be thrown. So for NSCoding defined initializers implemented in Objective-C, it should add a default error to them when bridging them to Swift if the failable initializer was removed and the designated initializer in NSCoding was re-defined with an initializer throws error info.

How do you guys think of that?

Thanks for reading.

WeZZard

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151227/0d59d6d9/attachment.html>


More information about the swift-evolution mailing list