concept flatMapError in category swift

appears as: flatMapError
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

Before we finish up, you’ll see how to perform clean error handling with Result by using the elusive flatMapError method.

Figure 11.6. Calling flatMapError on Result
Listing 11.17. Error recovery using flatMapError
enum WeatherError: Error {                                                 #1
    case loadingFailed
    case couldNotParseData
}

func loadWeatherReport(completion: @escaping (Result<WeatherReport,
     WeatherError>) -> Void) {                                             #2
    loadData(url: URL(string: "https://api.myweatherstartup.com")!) {
     (result: Result<Data, Error>) in                                      #3
        let transformedResult =                                            #4
            result
                .flatMap { (data: Data) -> Result<WeatherReport, Error> in #5
                    return Result(catching: { try WeatherReport.init(data: #5
     data) })                                                              #5
                }
                .flatMapError({ (error: Error) -> Result<WeatherReport,
     WeatherError> in                                                      #6
                    guard error is WeatherError else {
                        return Result.failure(WeatherError.loadingFailed)  #7
                    }

                    // Parsing failed, let's return a hard-coded
     WeatherReport
                    let weatherReport = WeatherReport(fahrenheit: 68,
     pressure: 1012, humidity: 81, windSpeed: 4, description: "windy")
                    return Result.success(weatherReport)                   #8
                })

        completion(transformedResult)                                      #9
    }
}

loadWeatherReport { (result: Result<WeatherReport, WeatherError>) in       #10
    switch result {
        case .success(let weatherReport):
            print("Received \(weatherReport)")
        case .failure(let error):
            print("Could not load weather report \(error)")
    }
}