In computer programming, the pyramid of doom is a common problem that arises when a program uses many levels of nested indentation to control access to a function. It is commonly seen when checking for null pointers or handling callbacks.
This quote from Wikipedia simply explains what pyramid of doom is. It's really easy in modern programming languages to encounter the issue, especially when executing asynchronous code.
Futures and promises are designed to resolve this problem. Some languages offer native solutions, but when it comes to Obj-C and Swift there is a pretty cool third-party library that allows handling it easily: PromiseKit.
Its syntax is similar to reactive programming patterns, such as RxSwift. To be honest I'm pretty sure that using both RxSwift and PromiseKit at the same time is pointless.
PromiseKit uses a generic Promise class to represent asynchronous tasks. They are only as useful as tasks they represent. At the moment, almost all Apple's APIs are converted to promises. You can find all official extensions here.
When you use them, you don't have to write your own promises in most cases, but in case you actually need to write one, it will be really simple!
This one shows a network activity indicator at first, then calls the promise above. It is converted inside the map block to a String and then printed to the debug console if the promise is fulfilled. After this, the ensure block is called (it doesn't matter whether the promise is fulfilled or rejected) to hide an activity indicator. If the promise fails (this particular one cannot fail, as it's always fulfilled and never rejected), the error's localised description will be printed.
Let's build something useful!
It's hard to say that the promise above is useful. Don't waste time and create a new project with PromiseKit and PromiseKit/CoreLocation in your Podfile.
We're going to build a simple app that gets your current location, sends a request for the current weather and shows the temperature, and then gets an icon with your current weather conditions.
To make it with standard API, you need at least a hundred lines of code, but with PromiseKit a dozen and a half would be enough.
First, let's create the properties for UI elements. We need two labels and one image view. I prefer storyboards for such small projects, so here goes my IBOutlets.
@IBOutlet private weak var cityLabel: UILabel!
@IBOutlet private weak var weatherImageView: UIImageView!
@IBOutlet private weak var temperatureLabel: UILabel!
Then add two simple functions that help generate URL for requests.