How to use Dictionary in Swift?

75 views Asked by At

I created Dictionary like below,

   let bookList = [
    ["title" : "Harry Potter",
     "author" : "Joan K. Rowling"
     "image" : image // UIImage is added.
    ],
    ["title" : "Twilight",
     "author" : " Stephenie Meyer",
     "image" : image
    ],
    ["title" : "The Lord of the Rings",
     "author" : "J. R. R. Tolkien",
     "image" : image]

and I'd like to make a tableView using this book list.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "listCell") as? ListCell else { return UITableViewCell() }
        let book = bookList[indexPath.row]

        cell.configureCell(title: book.???, author: ???, bookImage: ???)
        return cell
    }

How should I use value and key of Dictionary to configure Cell?

2

There are 2 answers

0
vadian On

It's highly recommended to use a custom struct rather than a dictionary

struct Book {
   let title : String
   let author : String
   let image : UIImage
}

var bookList = [Book(title: "Harry Potter", author: "Joan K. Rowling", image: image),
                Book(title: "Twilight", author: "Stephenie Meyer", image: image),
                Book(title: "The Lord of the Rings", author: "J. R. R. Tolkien", image: image)]

The huge benefit is you have distinct non-optional types without any type cast

let book = bookList[indexPath.row]
cell.configureCell(title: book.title, author: book.author, bookImage: book.image)

Further I'd declare configureCell

func configureCell(book : Book)

and pass

cell.configureCell(book: bookList[indexPath.row])

Then you can assign the members of the struct directly to the labels in configureCell

1
vacawama On

A dictionary is not your best structure here.

The problem with the dictionary is that you have to handle the casting of the type (since your dictionary is [String: Any]) and dealing with the fact that a dictionary lookup is Optional because a key might be missing.

You could do (not recommended):

cell.configureCell(title: book["title"] as? String ?? "", author: book["author"] as? String ?? "", bookImage: book["image"] as? UIImage ?? UIImage(named: default))

See how painful that is?

Instead, use a custom struct to represent your book:

struct Book {
    var title: String
    var author: String
    var image: UIImage
}


let bookList = [
    Book(
        title : "Harry Potter",
        author : "Joan K. Rowling",
        image : image // UIImage is added.
    ),
    Book(
        title : "Twilight",
        author : " Stephenie Meyer",
        image : image
    ),
    Book(
        title : "The Lord of the Rings",
        author : "J. R. R. Tolkien",
        image : image
    )
]

Then your configuration simply becomes:

cell.configureCell(title: book.title, author: book.author, bookImage: book.image)