【发布时间】:2015-01-28 05:42:54
【问题描述】:
我正在尝试使用一个 API,其中每个对象都以不同的方式命名其 ID 字段。示例:Group.groupid、Team.teamid 等
我有一个BaseAPIObject,它有一个接受解析的 JSON 字典的必需初始化程序和一个只接受 ID 字段(我的类的唯一必需属性)的便利初始化程序。
我已经通过添加一个返回 ID 字段名称的静态又名“类”方法来处理不断变化的 id 字段名称,并且子类会覆盖该函数以返回它们自己的字段名称。
我遇到的问题是,在我的基类的便利初始化程序中,我不能在调用 self.init() 之前调用 self.dynamicType,但我需要该静态类函数的结果才能正确构造我的对象。
public class BaseAPIObject {
var apiID: String!
var name: String?
var createdBy: String?
var updatedBy: String?
//Construct from JSONSerialization Dictionary
required public init(_ data: [String: AnyObject]) {
name = data["name"] as String?
createdBy = data["created_by"] as String?
updatedBy = data["updated_by"] as String?
super.init()
let idName = self.dynamicType.idFieldName()
apiID = data[idName] as String?
}
/// Creates an empty shell object with only the apiID set.
/// Useful for when you have to chase down a nested object structure
public convenience init(id: String) {
// THIS is what breaks! I can't call self.dynamicType here
// How else can I call the STATIC CLASS method?
// in ObjC this would be as simple as self.class.getIdFieldName()
let idFieldName = self.dynamicType.getIdFieldName()
let data = [idFieldName: id]
self.init(data)
}
//This gets overridden by subclasses to return "groupid" or whatever
class func idFieldName() -> String {
return "id"
}
}
问题:如何解决在 instance 本身上运行 init 之前调用子类的 类函数 的问题?
【问题讨论】:
标签: swift initialization