1
我創建了User
類,並給出了使用字典作爲存儲機制的建議,以使它更加靈活並滿足我的需求。請參考question。Swift模型的最佳實踐
這是我原來的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")
任何表的模型任何表格。
如果我將模型名稱更改爲更廣泛的範圍,並將其重用於任何要從中抽取數據的表,我是否需要使用特定於模型的方法?
我同意@duncanC,但如果您確實需要保留內部字典存儲,您應該爲各種屬性創建離散計算屬性並使用代碼訪問基礎字典 – Paulw11