Swift 4:无法指定类型'[X]'的值来键入'[VC.X]'

时间:2018-02-22 12:21:17

标签: ios json swift

如何消除此编译器错误?如果我在函数中声明项目,那么一切都有效。

class VC: UIViewController {
    struct X: Decodable  {
        let id: String
        let name: String
        let url: String
    }
    var items = [X]()

    //-----------------------------

    func somefunc()  {
        do {
            // the error is here:
            self.items = try JSONDecoder().decode([X].self, from: data)    <<<<<<<<<<< Compile error is here
        }
        catch  let err  {
        }
    }
}         // class VC

1 个答案:

答案 0 :(得分:1)

应该正常工作(我尝试过并且没有编译器错误),但是,也许你已经有了一些同名的其他类/结构。尝试使用它只是为了确保:

self.items = try JSONDecoder().decode([VC.X].self, from: data)