[swift-evolution] Extending Failable Initializers

Brent Royal-Gordon brent at architechies.com
Fri Dec 4 19:29:31 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 }

You can get this kind of behavior with higher-order programming:

	var someString: String? = “1”
	guard let someInt = someString.flatMap(Int.init) else { return }

This says “if someString is nil, return nil; otherwise, initialize an Int passing the unwrapped value, and return the result”.

In general, Optional.map and Optional.flatMap let you do optional-chaining-like things in a much more general way. They’re pretty neat!

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list