[英]Cannot call value of non-function type 'Object'
我在嘗試解析 json 時出錯,我不知道實際出了什么問題。 因為我想保存 object 的迭代並出現錯誤
無法調用非函數類型“電影”的值
你能告訴我為什么是錯誤嗎? 這是我的代碼
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)
}
表達方式
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)
}
}
使用三個(!)不同的movie
變量。 這使編譯器感到困惑。 例如重命名方法
private static func createMovie(fromJSON movie: Movie) -> Movie? { ...
和
if let movie = createMovie(fromJSON: movie) {
items.append(movie)
}
順便說一句,您的大部分代碼都是多余的。 並且永遠不要在Decoding
上下文中返回無意義的自定義錯誤,返回真正的DecodingError
。
實際上你可以用這個替換你的整個代碼
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 }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.