【问题标题】:Cannot find 'ModelA' in scope using generic types使用泛型类型在范围内找不到“ModelA”
【发布时间】:2021-06-14 10:54:43
【问题描述】:

我有一个使用泛型类型的调用 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()
        }
        
    }
    
}

【问题讨论】:

    标签: ios swift generics codable


    【解决方案1】:

    在末尾添加自我。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 2021-09-21
      • 2021-08-01
      • 2022-01-16
      • 2021-08-03
      • 2021-11-29
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多