[英]Type 'MovieSearchContainer.Type' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
I wrote a generic function, but I get an error when using this function.我写了一个通用的 function,但是在使用这个 function 时出现错误。 What is the cause of this error?
这个错误的原因是什么? I added Codable to my models.
我将 Codable 添加到我的模型中。 I could not find the cause of this problem.
我找不到这个问题的原因。
Error错误
Type 'MovieSearchContainer.Type' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
Model Model
struct MovieSearchContainer: Codable {
var page: Int
var results: [MovieSearch]
}
struct MovieSearch: Codable {
var id: Int
var title: String
}
MovieService电影服务
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
}
}
}
The generic T can be inferred by the compiler with the completion closure in your case在您的情况下,编译器可以使用完成闭包推断通用 T
func fetchNewspaper<T: Codable>(stringUrl: String, completion: @escaping (T) -> ())
service.fetchNewspaper(stringUrl: url) { (result: MovieSearchContainer) in
// ...
}
unless you want to explicitly passing on the model type in which case除非您想明确传递 model 类型,在这种情况下
func fetchNewspaper<T: Codable>(stringUrl: String, model: T.Type, completion: @escaping (T) -> ())
service.fetchNewspaper(stringUrl: url, model: MovieSearchContainer.self) { result in
// ...
}
For more information on Swift Generics, refer to the official docs有关 Swift Generics 的更多信息,请参阅 官方文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.