在 Swift 中使用结构的 JSON 解码器没有成员错误问题

Has No Member Error Issue with JSON Decoder using Structs in Swift

我使用 https://app.quicktype.io/ 创建结构来解码一些 JSON 并成功解码。

但是,当我尝试访问主对象中的元素时,出现没有成员错误,如下所示:

Value of type 'myClass.BookReturned?' has no member 'title'.

这是 JSON 的样子:

{"book":[{"title":"Dreams of Trespass","author":"Fatimah Mernisse","pic":""}]}

struct BookReturned: Codable {
        let book: [Book]
    }
    
    //  Book
struct Book: Codable {
        let title, author, pic: String
    }

这是第二行出现错误的代码的样子

let mybook = try? JSONDecoder().decode(BookReturned.self, from: data)
let author = mybook.title//GIVES THE ERROR

获得称号的正确方法是什么?如果 JSON 格式不正确,我也可以更改 JSON。

请查看结构 BookReturned。确实没有会员title.

你必须得到数组的第一项book,还有title

let title = mybook.book.first?.title

如果数组包含更多项,则需要循环。