user6631314
user6631314

Reputation: 1960

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

I used https://app.quicktype.io/ to create the structs to decode some JSON and it decodes it successfully.

However, when I try to access the elements within the main object, I am getting a has no member error as follows:

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

This is what the JSON looks like:

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

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

This is what the code looks like with the error occuring on the second line

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

What is the proper way to get the title? If the JSON is malformed, I have the ability to change the JSON as well.

Upvotes: 0

Views: 1090

Answers (1)

vadian
vadian

Reputation: 285039

Please look at the struct BookReturned. There is indeed no member title.

You have to get the first item of the array book, there is the title

let title = mybook.book.first?.title

If the array contains more items you need a loop.

Upvotes: 2

Related Questions