使用泛型类型在作用域中找不到'ModelA'



我有一个使用泛型类型的调用api函数和参数
我还创建了一个可编码的数据模型
为什么函数参数没有得到我的自定义结构模型并得到错误Cannot find 'ModelA' in scope
我的T型错误吗
我不知道怎么修。
谢谢。

struct ResponseHeader :Codable  {
let returnCode : String?
let returnMsg  : String?
}
struct ModelA :Codable {
let responseHeader : ResponseHeader?
let responseBody   : ResponseBody?
struct ResponseBody: Codable {
let name : String?
let age  : String?
let email: String?
}
}
enum APIRouter: String {
case apiA = "http://localhost:3000/ApiA"
case apiB = "http://localhost:3000/ApiB"
case apiC = "http://localhost:3000/ApiC"
}
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

self.callApi(apiRouter: .apiA, model: ModelA) //Error. Cannot find 'ModelA' in scope
}

func callApi<T: Codable>(apiRouter: APIRouter, model: T.Type) {

let urlString = URL(string: apiRouter.rawValue)

if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

guard error == nil else { return }

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

if let data = data {

do {
let response = try decoder.decode(model.self, from: data)
print(response)
} catch {
print(error)
}

} else {
print("Error")
}

}

task.resume()
}

}

}

在末尾添加self。

此泛型函数将模型的实例类型作为参数,因此必须传递ModelA.self

self.callApi(apiRouter: .apiA, model: ModelA.self) //Here

最新更新