如何在Swift中使用Dictionary?

问题描述 投票:0回答:2

我创建了如下的字典,

   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的值和键来配置Cell?

swift dictionary tableview swift-dictionary
2个回答
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)

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中的标签

© www.soinside.com 2019 - 2024. All rights reserved.