简体   繁体   English

无法调用非函数类型“对象”的值

[英]Cannot call value of non-function type 'Object'

I have an error while trying to parse json, I don't know what went wrong actually.我在尝试解析 json 时出错,我不知道实际出了什么问题。 since I want to save the iteration of an object and an error appear因为我想保存 object 的迭代并出现错误

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.使用三个(!)不同的movie变量。 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 .并且永远不要在Decoding上下文中返回无意义的自定义错误,返回真正的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 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM