1
0

Reflection.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Relfection.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public protocol DatabaseReflectionProtocol {
  9. var id: UInt64? { get }
  10. init()
  11. }
  12. public class DatabaseReflection: DatabaseReflectionProtocol {
  13. public var id: UInt64? = nil
  14. required public init() { }
  15. }
  16. public extension DatabaseReflectionProtocol {
  17. public func schemeWithValuesMethod1() -> (String, [String: Any?]) {
  18. let reflections = _reflect(self)
  19. var fields = [String: Any?]()
  20. for index in 0.stride(to: reflections.count, by: 1) {
  21. let reflection = reflections[index]
  22. fields[reflection.0] = reflection.1.value
  23. }
  24. return (reflections.summary, fields)
  25. }
  26. public func schemeWithValuesMethod2() -> (String, [String: Any?]) {
  27. let mirror = Mirror(reflecting: self)
  28. var fields = [String: Any?]()
  29. for case let (label?, value) in mirror.children {
  30. fields[label] = value
  31. }
  32. return ("\(mirror.subjectType)", fields)
  33. }
  34. public static func classInstanceWithSchemeMethod1() -> (Self, String, [String: Any?]) {
  35. let instance = Self()
  36. let (name, fields) = instance.schemeWithValuesMethod1()
  37. return (instance, name, fields)
  38. }
  39. public static func classInstanceWithSchemeMethod2() -> (Self, String, [String: Any?]) {
  40. let instance = Self()
  41. let (name, fields) = instance.schemeWithValuesMethod2()
  42. return (instance, name, fields)
  43. }
  44. static func find(id: UInt64) -> Self? {
  45. let (instance, _, _) = classInstanceWithSchemeMethod1()
  46. // TODO - make a query to DB
  47. return instance
  48. }
  49. func insert() throws {
  50. // Stub.
  51. }
  52. func update() throws {
  53. // Stub.
  54. }
  55. }