Working with an array within an array - Swift -
i have array of books. books have title , characters. characters have name , age. both book , character structs.
when app launches set of default books created (the user add own later.
here basic code:
(note: ???? placeholder code can't solve.)
struct character { var name: string var age: int } struct book { var title: string var characters: [character] } var books: [book] = [] func createbooks() { books.append(book(title: "my book1", characters: ????) }
i know create array of characters , assign
books.append(book(title: "my book1", characters: [character[0], character[3]])
but i'm concerned handling 2 separate arrays become difficult in big list of books, not mention user created books.
how best handle this?
your question bit unclear here how this.
struct character { var name: string var age: int } struct book { var title: string var characters: [character] } var books: [book] = [] func createbooks() { let character1 = character(name: "john", age: 24) let character2 = character(name: "sarah", age: 18) books.append(book(title: "my book1", characters: [character1, character2])) }
that way a defined structure, can loop of books so:
for book in books { // book }
and can loop on characters of every book so:
for book in books { character in book.characters { // character } }
also agree comment leo dabus, should change name of character struct else bookcharacter in order avoid confusion between char , character in code.
Comments
Post a Comment