[swift-evolution] Extending Failable Initializers

Manav Gabhawala manav1907 at gmail.com
Fri Dec 4 18:49:22 CST 2015


Its possible to extend the functionality of failable initializers beyond what they are capable of by making the parameters failable too. For instance:


	var someString : String? = “1” // Assume for some reason this is optional
		
	// Here the Int’s failable initializer allows for an optional Int even
	// though it was only actually written for a non optional type because 
	// the failable initializer fails when you give it a nil value.
	guard let someInt = Int(someString) 
	else { return }
	// There are many possible use cases for this:
		
	enum Some : String { case A, B, C }
	let optionalString: String? = “A"
	// This works too. 
	let value = Some(rawValue: optionalString)
	// And can be extended out too. 
	let image = NSImage(named: optionalString)


There are several reasons this can be beneficial. This allows you to initialize using optional types and can be really useful if you’re trying to initialize things with stuff downloaded from the network or when using NSUserDefaults, etc. That way you don’t need to explicitly bind everything you use to ensure non-null values twice but the failable initializers take care of it for you, so its kind of like chaining the nil value to the failable initializers.

Regards,
Manav Gabhawala



More information about the swift-evolution mailing list