swift - 从 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)
这部分是我收到构建错误的地方,转换其余部分基本上没问题。
解决方案
Swift 5 中的Result
类型基本上是
enum Result<Success, Failure> where Failure : Error {
case success(Success), failure(Failure)
}
如果您不需要init(catching
orget()
功能或map
基本枚举就足够了
推荐阅读
- c# - 如何创建一个与另一个重叠的网格并在第二个网格中显示第一个网格的某些控件
- c - 为什么在 K&R 8.7 的 free() 的“for”循环的“for”循环的增量部分的测试部分没有增量?
- vb.net - 我的项目似乎已构建,但错误不断发生,我无法找出原因
- mongodb - 在我的 mongodb 数据库中创建文档后不执行数据库操作
- javascript - 我如何调整这个切片并替换 React
- octave - 示例程序中的问题未定义变量
- javascript - 如何在javascript中从dom中删除元素?
- django - 如何使用 is_grater_priority 制作绿色主体
- javascript - 每次单击按钮时都从 firebase 读取数据,而无需刷新
- apache-spark-sql - 使用 Spark SQL 将表过滤到列的最小值的行