从 Swift 5 类型 <Result> 转换为 Swift 3 等价
Converting From Swift 5 Type <Result> to Swift 3 Equivalent
我正在尝试将一些 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 中的 Result.Type 相当于什么 3
func run(completion : @escaping (Result<String,Error>) -> Void)
这部分是我收到构建错误的地方,转换其余部分基本上没问题。
Result
类型Swift5基本就是
enum Result<Success, Failure> where Failure : Error {
case success(Success), failure(Failure)
}
如果您不需要 init(catching
或 get()
功能或 map
基本枚举就足够了
我正在尝试将一些 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 中的 Result.Type 相当于什么 3
func run(completion : @escaping (Result<String,Error>) -> Void)
这部分是我收到构建错误的地方,转换其余部分基本上没问题。
Result
类型Swift5基本就是
enum Result<Success, Failure> where Failure : Error {
case success(Success), failure(Failure)
}
如果您不需要 init(catching
或 get()
功能或 map
基本枚举就足够了