Reputation: 565
I have the following code:
class Book {
let title = ""
let description = ""
let ebookPath = ""
let featuredCategories = [FeaturedCategory]()
let authors = [Author]()
let publishers = [Publisher]()
//...
}
class FeaturedCategory {
let name = ""
let books = [Book]()
}
class Author {
let name = ""
let books = [Book]()
}
class Publisher {
let name = ""
let books = [Book]()
}
class Tag {
let name = ""
let books = [Book]()
}
As you can see from the code above, there is a lot of repetition. This becomes even more ugly if I add more classes with the same variables name
and books
. What is a better alternative?
Edit: I'm downloading JSON from Firebase. Here's the JSON structure:
...
Upvotes: 0
Views: 66
Reputation: 15512
Hmm this question could be answered in many ways but i will try to share my opinion on it.
Firstly try to use struct
instead of the class
because in this way you are more flexible in architecture.
Secondly use protocol
for creating of the relationships.
Small example :
//Struct insted of class
struct Book {
//Usage of the let in struct is good practice.
let title: String
let description: String
let ebookPath: String
let featuredCategories: [FeaturedCategory]
}
//Base protocol
protocol HasBooks {
var name: String { get }
var books: [Book] { get }
}
//Strcut that reuqires to implement name and books.
struct FeaturedCategory : HasBooks {
var name = ""
var books = [Book]()
}
Upvotes: 2