请考虑以下设置:
protocol MyProcotol {
}
class MyModel: MyProcotol {
}
enum Result<T> {
case success(value: T)
case failure
}
class Test {
func test<T: MyProcotol>(completion: (Result<T>) -> Void) {
let model = MyModel()
let result = Result.success(value: model)
completion(result)
}
}
为什么我不能拨打completion(result)
?我收到此错误:
无法转换类型&#39;结果&#39;预期参数类型&#39;结果&lt; _&gt;&#39;
任何解决方法?
答案 0 :(得分:4)
您在通用函数中使用非泛型具体类型MyModel
,但不起作用。
你可以做这样的事情
class Test {
func test<T: MyProcotol>(item: T, completion: (Result<T>) -> Void) {
let result : Result<T> = .success(value: item)
completion(result)
}
}
答案 1 :(得分:1)
您可以使用强制转换来转换潜在的通用值。
protocol MyProcotol {}
struct MyModel: MyProcotol {
let x: Int
}
struct TheirModel: MyProcotol {
let y: Int
}
enum Result<T> {
case success(value: T)
case failure
var value: T? {
switch self {
case .success(let value): return value
case .failure: return nil
}
}
}
struct Test {
enum ModelType {
case my, their
}
static func get<T: MyProcotol>(type: ModelType, completion: (Result<T>) -> Void) {
let model: Any
switch type {
case .my: model = MyModel(x: 42)
case .their: model = TheirModel(y: 19)
}
if let value = model as? T { completion(.success(value: value)) }
else { completion(.failure) }
}
}
Test.get(type: .my) { (result: Result<MyModel>) in
guard let value = result.value else { return }
print("here is MyModel \(value) with value: \(value.x)")
}
Test.get(type: .their) { (result: Result<TheirModel>) in
guard let value = result.value else { return }
print("here is TheirModel \(value) with value: \(value.y)")
}
Test.get(type: .their) { (value: Result<MyModel>) in
print("here is failure? \(value)")
}