我有以下代码:
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]()
}
从上面的代码中可以看出,有很多重复。如果我添加更多具有相同变量name
和books
的类,这会变得更加难看。什么是更好的选择?
编辑:我从Firebase下载JSON。这是JSON结构:
...
答案 0 :(得分:2)
嗯,这个问题可以通过多种方式得到解答,但我会尝试分享我对此的看法。
首先尝试使用struct
代替class
,因为通过这种方式,您可以更灵活地构建。
其次使用protocol
来创建关系。
小例子:
//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]()
}