I have an error while trying to parse json, I don't know what went wrong actually. since I want to save the iteration of an object and an error appear
Cannot call value of non-function type 'Movie'
can you tell me why is error? this is my code
static func movies(fromJSON data: Data) -> Result<[Movie], MovieError> {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let jsonData = try decoder.decode(MovieItem.self, from: data)
var items = [Movie]()
for movie in jsonData.results {
// this is the line an error appear in movie(fromJSON: movie)
if let movie = movie(fromJSON: movie) {
items.append(movie)
}
}
return .success(items)
} catch {
return .failure(.failedToParseJSON)
}
}
private static func movie(fromJSON movie: Movie) -> Movie? {
let id = movie.id
let title = movie.title
let releaseDate = movie.releaseDate
let overview = movie.overview
let posterPath = movie.posterPath
return Movie(id: id, title: title, releaseDate: releaseDate, overview: overview, posterPath: posterPath)
}
The expression
for movie in jsonData.results {
// this is the line an error appear in movie(fromJSON: movie)
if let movie = movie(fromJSON: movie) {
items.append(movie)
}
}
uses three(!) different movie
variables. This confuses the compiler. Rename the method for example
private static func createMovie(fromJSON movie: Movie) -> Movie? { ...
and
if let movie = createMovie(fromJSON: movie) {
items.append(movie)
}
By the way most of your code is redundant. And never return a meaningless custom error in a Decoding
context, return the real DecodingError
.
Actually you can replace your entire code with this
static func movies(fromJSON data: Data) -> Result<[Movie], Error> {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return Result{ try decoder.decode(MovieItem.self, from: data).results }
}
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.