微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型“MovieSearchContainer.Type”不能符合“Decodable”;只有结构/枚举/类类型可以符合协议

如何解决类型“MovieSearchContainer.Type”不能符合“Decodable”;只有结构/枚举/类类型可以符合协议

我编写了一个通用函数,但在使用该函数时出现错误。这个错误的原因是什么?我将 Codable 添加到我的模型中。我找不到这个问题的原因。

错误

Type 'MovieSearchContainer.Type' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols

模型

struct MovieSearchContainer: Codable {
    var page: Int
    var results: [MovieSearch]
}

struct MovieSearch: Codable {
    var id: Int
    var title: String
}

电影服务

class MovieBaseService {
    func fetchNewspaper<T: Codable>(stringUrl: String,model: T,completion: @escaping (T) -> ()) {
        if let url = URL(string:stringUrl) {
            let session = URLSession(configuration: .default)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            
            request.addValue("application/json",forHTTPHeaderField: "Content-Type")
            request.addValue("application/json",forHTTPHeaderField: "Accept")
            
            let task = session.dataTask(with: request as URLRequest) { (data,response,error) in
                if error == nil {
                    let decoder = JSONDecoder()
                    if let movieData = data {
                        do {
                            let results = try decoder.decode(T.self,from: movieData)
                            completion(results)
                        } catch {
                            print(error)
                        }
                    }
                }
            }
            task.resume()
        }
    }
}

SearchMovieVM

class SearchMovieVM: ObservableObject {
    var searchMovieService = MovieBaseService()
    @Published var searchedMovie: [MovieSearch] = []
    @Published var query: String = ""
    @Published var page: Int = 1
    
    func getSearchingMovie() {
        self.searchMovieService.fetchNewspaper(stringUrl: "https://api.themoviedb.org/3/search/movie?api_key=594b8eb4999a8b44ad5136ee3ed1ebdb&language=tr-TR&query=\(query)&page=1&include_adult=false",model: MovieSearchContainer) { (result) in
            
        }
    }
}

解决方法

编译器可以推断出泛型 T,并在您的情况下使用完成闭包

func fetchNewspaper<T: Codable>(stringUrl: String,completion: @escaping (T) -> ())

service.fetchNewspaper(stringUrl: url) { (result: MovieSearchContainer) in
    // ...
}

除非在这种情况下您想显式传递模型类型

func fetchNewspaper<T: Codable>(stringUrl: String,model: T.Type,completion: @escaping (T) -> ())

service.fetchNewspaper(stringUrl: url,model: MovieSearchContainer.self) { result in
    // ...
}

有关 Swift 泛型的更多信息,请参阅 official docs

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。