2015-10-24 183 views
1

我創建了User類,並給出了使用字典作爲存儲機制的建議,以使它更加靈活並滿足我的需求。請參考questionSwift模型的最佳實踐

這是我原來的User型號:

下面是使用字典作爲存儲機制,我更新User類:

final class User: NSObject, ResponseObjectSerializable, ResponseCollectionSerializable { 

    var properties = NSDictionary() 

    init?(response: NSHTTPURLResponse, representation: AnyObject) { 
     if let dataRepresentation = ((representation as! NSDictionary).valueForKey("data") as? [String: AnyObject]) { 
      properties = dataRepresentation 
     } 

     properties = representation as! NSDictionary 
    } 

    static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { 
     var users: [User] = [] 

     if let dataRepresentation = ((representation as! NSDictionary).valueForKey("data") as? [NSDictionary]) { 
      if let dataRepresentation = dataRepresentation as? [[String: AnyObject]] { 
       for userRepresentation in dataRepresentation { 
        if let user = User(response: response, representation: userRepresentation) { 
         users.append(user) 
        } 
       } 
      } 
     } 

     return users 
    } 
} 

想到的,雖然這個問題,是如何將另一位程序員知道他可以從User模型中獲取哪些字段,因爲我不再將它們單獨存儲爲變量。他們只需要檢查數據庫並查看錶格的結構?

另外,User類是設置現在的樣子,它幾乎可能是我從數據庫中提取(因爲我有它現在沒有User模型具體方法),我可以隨時調用user.properties.valueForKeyPath("column_name")任何表的模型任何表格。

如果我將模型名稱更改爲更廣泛的範圍,並將其重用於任何要從中抽取數據的表,我是否需要使用特定於模型的方法?

+0

我同意@duncanC,但如果您確實需要保留內部字典存儲,您應該爲各種屬性創建離散計算屬性並使用代碼訪問基礎字典 – Paulw11

回答

5

我傾向於將自定義數據對象替換爲字典。自定義數據對象具有特定的具體類型的命名字段。它是自我記錄的,當你使用它時,你可以假設它具有你期望的屬性,並且它們是正確的類型。用字典你不能假設(嗯,用Swift字典,你可以強制打字,但是你不能混合不同類型的屬性,如姓名字符串和數字工資值)