Generics and the Art of Inference Part 3 of 3

In the pre-generics days of Obj-C the only way to pass around things of unknown type was with an id type, but with Swift Generics/Protocols we can do things like Promises statically and safely with an associateType. Although large scale projects has been built in several Swift libraries already, we’ll look at how a barebones version can be written in under 40 lines of code and used in the context of your networking layer.

Modeling a Result enum type against how Optional is implemented in Foundation we create a Result type to contain a value of .somewith associated value generic type Wrapped or .error that would contain a BasicError

(1)The initializers are shortcuts that let us call Result(BasicError.unknown) or just Result(.unknown)

(2)fire unwraps the type using a switch and passes it into the correct Promise closure.

Our promise function stores a reference to the complete/failure functions until it recieves the Result via the trigger variable.
The async closure waiting to apply the Result to trigger will keep our Promise alive until it is fired.

Although this Promise implementation lacks the composability of a then, you can start to see how much we can accomplish with very little code.

Using this in the context of your networking layer might look like:

We can genericize this using a JSONDecodable constraint on a generic T to guarantee we can call init(object: [String: AnyObject]) throws.

Now the compiler can infer what is wrapped in our Promise using our complete function.

Also, thank you @nevyn for you feedback on this!