是否可以将以下方法作为方法的协议+扩展而不是类来防止它被用作可以实例化的类?
我遇到的问题是我无法使用自定义init进行构建。 Xcode一直在抱怨我在使用self,但是调用super.init也没有被接受。
class Entity: NSObject
{
var objectID: String?
var createdAt: NSDate?
var updatedAt: NSDate?
required override init()
{
}
required init(dictionary: Dictionary)
{
if let objectID = dictionary["objectId"] as? String
{
self.objectID = objectID
}
if let createdAt = dictionary["createdAt"] as? String
{
self.createdAt = NSDate.dateFromJSONDateString(createdAt)
}
if let updatedAt = dictionary["updatedAt"] as? String
{
self.updatedAt = NSDate.dateFromJSONDateString(updatedAt)
}
}
func dictionaryRepresentation() -> Dictionary
{
var dict = Dictionary()
if let objectID = objectID
{
dict["objectId"] = objectID
}
if let createdAt = createdAt
{
dict["createdAt"] = createdAt.JSONDateString()
}
if let updatedAt = updatedAt
{
dict["updatedAt"] = updatedAt.JSONDateString()
}
return dict
}
}
基本上我想实现所有符合Entity的类都有一个objectID,createdAT和updatedAt,可以用字典初始化并获得一个dictionaryRepresentation for。
答案 0 :(得分:3)
您可以使用协议,协议扩展和结构来完成此任务。
基本协议:
protocol Entitable {
var objectID: String? { get set }
var createdAt: NSDate? { get set }
var updatedAt: NSDate? { get set }
init()
}
STRUCT:
struct Entity:Entitable {
var objectID: String?
var createdAt: NSDate?
var updatedAt: NSDate?
init() {
}
}
扩展:
extension Entitable {
init(dictionary: Dictionary<String, AnyObject>) {
self.init()
if let objectID = dictionary["objectId"] as? String {
self.objectID = objectID
}
if let createdAt = dictionary["createdAt"] as? String {
self.createdAt = NSDate.dateFromJSONDateString(createdAt)
}
if let updatedAt = dictionary["updatedAt"] as? String {
self.updatedAt = NSDate.dateFromJSONDateString(updatedAt)
}
}
func dictionaryRepresentation() -> Dictionary<String, AnyObject> {
var dict = Dictionary<String, AnyObject>()
if let objectID = objectID {
dict["objectId"] = objectID
}
if let createdAt = createdAt {
dict["createdAt"] = createdAt.JSONDateString()
}
if let updatedAt = updatedAt {
dict["updatedAt"] = updatedAt.JSONDateString()
}
return dict
}
}