首页 > 解决方案 > 从 Swift 5 类型转换相当于 Swift 3

问题描述

我正在尝试将一些 Swift 5 转换为 Swift 3,因为我遇到了向后兼容性问题。

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()
    }
}

在 Swift 3 中相当于 Result.Type func run(completion : @escaping (Result<String,Error>) -> Void)这部分是我收到构建错误的地方,转换其余部分基本上没问题。

标签: swiftswift3swift5

解决方案


Swift 5 中的Result类型基本上是

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

如果您不需要init(catchingorget()功能或map基本枚举就足够了


推荐阅读