0

我创建了如下字典,

   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]

我想用这个书单制作一个tableView。

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
    }

我应该如何使用 Dictionary 的 value 和 key 来配置 Cell?

4

2 回答 2

1

强烈建议使用自定义结构而不是字典

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)]

巨大的好处是你有不同的非可选类型,没有任何类型转换

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

此外,我会声明configureCell

func configureCell(book : Book)

并通过

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

然后您可以将结构的成员直接分配给中的标签configureCell

于 2017-12-16T13:56:23.397 回答
1

字典不是你最好的结构。

字典的问题是您必须处理类型的转换(因为您的字典是[String: Any])并处理字典查找是可选的事实,因为可能缺少键。

你可以这样做(不推荐):

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

看看有多痛?

相反,使用自定义struct来表示您的书:

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
    )
]

然后你的配置就变成了:

cell.configureCell(title: book.title, author: book.author, bookImage: book.image)
于 2017-12-16T13:56:26.120 回答