2016-12-07 54 views
0

我有以下代碼:如何更好地構建這些數據?

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

正如你可以從上面的代碼中看到,有很多重複的。如果我使用相同的變量namebooks添加更多類,這會變得更加難看。什麼是更好的選擇?

編輯:我正在從Firebase下載JSON。這裏的JSON結構:

enter image description here

...

enter image description here

+0

將是一件好事,包括在這個問題的更多細節。 「這個數據」非常模糊。 – Luke

+0

你有上面的JSON嗎? –

+0

請檢查編輯 –

回答

2

嗯,這個問題可以在很多方面來回答,但我會盡力分享它我的意見。

首先嚐試使用struct而不是class,因爲通過這種方式,您在架構上更加靈活。

其次使用創建關係。

小例子:

//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]() 
} 
+0

我會爲協議選擇一個類似HasBooks的名稱。無論如何,它比BaseData更具描述性。 – Fogmeister

+1

我編輯我的答案,你有正確的建議。 –

+0

這是一個更好的改進,但是如果我有,比方說20個具有相同確切數據的結構?這不會太奇怪嗎? –

相關問題