Search code examples
swiftswift3swift5

Converting From Swift 5 Type <Result> to Swift 3 Equivalent


I am trying to convert some Swift 5 to Swift 3 as I am having issues with backwards compatibility.

import Foundation
class WS {
    enum WebSessionError : Error {
        case badResponse(String)
    }
    // RequestURL -> API Location
    static let requestURL = URL(string:"-Placeholder-")!
    static var sharedInstance = WS() // Instancing our class
    func run(completion : @escaping (Result<String,Error>) -> Void) {
        let instancedTask = URLSession.shared.dataTask(with: WS.requestURL)
        { (data,response,error) in
            if let error = error {
                print("Client Error: \(error.localizedDescription)")
                completion(.failure(error))
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode)
                else {
                    completion(.failure(WebSessionError.badResponse("Server Error!")))
                return
            }
            guard let mime = response.mimeType, mime == "text/html" else {
                    completion(.failure(WebSessionError.badResponse("Wrong mime type!")))
                return
            }
            completion(.success(String(data: data!, encoding: .utf8)!))
        }
        instancedTask.resume()
    }
}

What would be the equivalent of Result.Type in Swift 3 func run(completion : @escaping (Result<String,Error>) -> Void) this portion being where I am receiving build errors, converting the rest has been mostly okay.


Solution

  • The Result type in Swift 5 is basically

    enum Result<Success, Failure> where Failure : Error {
        case success(Success), failure(Failure)
    }
    

    If you don't need the init(catching or get() functionality or the map stuff the basic enum is sufficient