2017-12-16 12 views
0

私は、以下のような辞書を作成しDictionary in Swiftの使い方は?

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 
    } 

セルを構成するために辞書の値とキーはどのように使用しますか?

答えて

1

非常に大きなメリットがどのようなタイプが

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

さらにIをキャストすることなく、あなたは明確な非オプションの種類を持っている辞書

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

ではなく、独自の構造体を使用することをお勧めします'宣言するconfigureCell

func configureCell(book : Book) 

とその後あなたは辞書はここにあなたの最高の構造ではないconfigureCell

1

のラベルに直接構造体のメンバーを割り当てることができます

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

を渡します。

辞書の問題は、あなたが(あなたの辞書が[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) 
+0

偉大な心は確かに似 – vadian

+0

と思います。私たちの2人がそれを言うときに考える価値があるアイデアであることは、OPにもっと説得力があります。 – vacawama