所以我正在尝试在Swift中构建数据映射器样式的ORM。我试图找到一种方法将任何实体转换为字典,以便我可以将其映射到数据库表。我设法用这段代码做到了:
现在我可以做到:
public protocol Entity: class {
var id: Int? { get set }
}
func unwrap(any:Any) -> Any? {
let mi = Mirror(reflecting: any)
if mi.displayStyle != .Optional {
return any
}
if mi.children.count == 0 {
return nil
}
let (_, some) = mi.children.first!
return some
}
public func serialize<T: Entity>(entity: T) -> [String:String] {
let aMirror = Mirror(reflecting: entity)
var dict = [String:String]()
for child in aMirror.children {
if let label = child.label where !label.hasPrefix("_") {
switch unwrap(child.value) {
case let entity as Entity:
if let id = entity.id {
dict[label] = String(id)
}
case let .Some(test):
dict[label] = String(test)
default: break
}
}
}
return dict
}
public class User: Entity {
public var id: Int?
var username: String
var password: String
var role: UserRole?
public init(username: String, password: String) {
self.username = username
self.password = password
}
public func assignRole(role: UserRole) {
self.role = role
}
}
public class UserRole: Entity {
public var id: Int?
var name: String
var description: String
public init(name: String, description: String) {
self.name = name
self.description = description
}
}
将打印:let newUser = User(username: "NotMyRealName", password: "SomeKindOfPassword")
let adminRole = UserRole(name: "admin", description: "Administrator of the website")
adminRole.id = 1
newUser.assignRole(adminRole)
print(serialize(newUser))
这一切都很好,但现在我想扭转这个过程。
我想编写一个可以这样使用的函数:
["password": "SomeKindOfPassword", "role": "1", "username": "NotMyRealName"]
你能想到吗?我知道如果我试图绕过init方法可能会有点麻烦,但我想尝试一下。