Advertisement
Guest User

Untitled

a guest
May 27th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public protocol PropertyDescribing {
  2. associatedtype Content
  3. var name: String { get }
  4. }
  5.  
  6. public struct PropertyDescriptor<Content>: PropertyDescribing {
  7. // ...
  8. }
  9.  
  10. public struct UnsafePropertyDescriptor: PropertyDescribing {
  11. public typealias Content = Any
  12. // ...
  13. }
  14.  
  15. @magic protocol Reflectable {
  16. public static func properties: [String]
  17. public static func unsafeDescriptor(forProperty name: String) throws -> UnsafePropertyDescriptor
  18. /// needn't be inferred from the return type if the specializing function proposal is accepted.
  19. public static func descriptor<Value>(forProperty name: String) throws -> PropertyDescriptor<Value>
  20.  
  21. public func getValue<Descriptor: PropertyDescribing>(using descriptor: Descriptor) -> Descriptor.Content
  22. /// Throws an error if the property is read-only.
  23. public mutating func setValue<Descriptor: PropertyDescribing>(value: Descriptor.Content, using descriptor: Descriptor) throws
  24. }
  25.  
  26. extension Reflectable {
  27. public func getValue(forProperty name: String) throws -> Any {
  28. return getValue(try Self.unsafeDescriptor(forProperty: name))
  29. }
  30.  
  31. public mutating func setValue(value: Any, forProperty name: String) throws {
  32. try setValue(value, using: try Self.unsafeDescriptor(forProperty: name))
  33. }
  34. }
  35.  
  36. func callSite() {
  37. let myObject = ReflectableClass()
  38.  
  39. /// Unsafe shorthand
  40. let description: Any = try! myObject.getValue(forProperty: "description")
  41.  
  42. /// Typed version.
  43. let descriptor = try! SomethingReflectable.descriptor<String>(forProperty: "descriptor")
  44. let description2: String = myObject.getValue(using: descriptor)
  45.  
  46. let myValue = ReflectableStruct()
  47.  
  48. /// BAMM!
  49. try! myValue.setValue("Testing", forProperty: "message") /// compiler warning: cannot mutate `myValue`.
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement