I wrote a generic function, but I get an error when using this function. What is the cause of this error? I added Codable to my models. 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
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.