Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. import Cocoa
  2.  
  3. // more of a POC
  4. // not production ready
  5.  
  6. protocol PropertyReflectable { }
  7.  
  8. extension PropertyReflectable {
  9. subscript(property key: String) -> Any? {
  10. let mirror = Mirror(reflecting: self)
  11. for child in mirror.children where child.label == key {
  12. return child.value
  13. }
  14. return nil
  15. }
  16.  
  17. var properties: [String] {
  18. return Mirror(reflecting: self).children.flatMap { $0.label }
  19. }
  20. }
  21.  
  22.  
  23. struct Templater {
  24. static func format(text: String, model: PropertyReflectable) -> String {
  25. var output = text
  26. for property in model.properties {
  27. if let value = model[property: property] {
  28. output = output.replacingOccurrences(of: "{{\(property)}}", with: "\(value)")
  29. }
  30. }
  31. return output
  32. }
  33.  
  34. static func format(text: String, model: [String: PropertyReflectable]) -> String {
  35. var output = text
  36. for (_, kv) in model.enumerated() {
  37. for property in kv.value.properties {
  38. let key = "\(kv.key).\(property)"
  39. if let value = kv.value[property: property] {
  40. output = output.replacingOccurrences(of: "{{\(key)}}", with: "\(value)")
  41. }
  42. }
  43. }
  44. return output
  45. }
  46. }
  47.  
  48. struct Person {
  49. let name: String
  50. let age: Int
  51. }
  52.  
  53. extension Person : PropertyReflectable { }
  54.  
  55. let me = Person(name: "Benzi", age: 5)
  56.  
  57. Templater.format(
  58. text: "my name is {{name}}, i am {{age}} years old",
  59. model: me
  60. )
  61.  
  62. // my name is Benzi, i am 5 years old"
  63.  
  64. struct Product {
  65. let name: String
  66. let price: Decimal
  67. }
  68.  
  69. extension Product : PropertyReflectable { }
  70.  
  71. let book = Product(name: "Starting Swift", price: 9.99)
  72.  
  73. Templater.format(
  74. text: "{{user.name}} just bought {{product.name}} ({{product.price}})",
  75. model: [
  76. "user": me,
  77. "product": book
  78. ]
  79. )
  80.  
  81. // "Benzi just bought Starting Swift (9.99)"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement