2017-12-16 3 views
0

나는사전을 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를하고 싶습니다.

사전의 값과 키를 사용하여 셀을 구성하는 방법은 무엇입니까?

답변

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) 

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

는 그런 다음 configureCell

1

사전에 직접 레이블 구조체의 멤버를 지정할 수 있습니다 통과 여기에 최고의 구조가 아닙니다.

사전의 문제는 당신이 (당신의 사전 [String: Any] 때문에) 유형의 캐스팅을 처리하고 키가 누락 될 수 있으므로 사전 조회가 옵션 사실을 처리해야한다는 것입니다.

당신이 할 수있는 (을 권장하지 않음) :

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

그게 얼마나 고통스러운보기?

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

큰 마음 – vadian

+0

실제로 모두 생각 :

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

그런 다음 구성이 간단하게 :

대신, 책을 표현하기 위해 사용자 정의 struct를 사용합니다. 그것은 우리 중 2 명이 그것을 말할 때 고려할만한 가치가있는 아이디어라는 점에서 OP에 더욱 설득력이 있습니다. – vacawama

관련 문제