Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public protocol PropertyDescribing {
- associatedtype Content
- var name: String { get }
- }
- public struct PropertyDescriptor<Content>: PropertyDescribing {
- // ...
- }
- public struct UnsafePropertyDescriptor: PropertyDescribing {
- public typealias Content = Any
- // ...
- }
- @magic protocol Reflectable {
- public static func properties: [String]
- public static func unsafeDescriptor(forProperty name: String) throws -> UnsafePropertyDescriptor
- /// needn't be inferred from the return type if the specializing function proposal is accepted.
- public static func descriptor<Value>(forProperty name: String) throws -> PropertyDescriptor<Value>
- public func getValue<Descriptor: PropertyDescribing>(using descriptor: Descriptor) -> Descriptor.Content
- /// Throws an error if the property is read-only.
- public mutating func setValue<Descriptor: PropertyDescribing>(value: Descriptor.Content, using descriptor: Descriptor) throws
- }
- extension Reflectable {
- public func getValue(forProperty name: String) throws -> Any {
- return getValue(try Self.unsafeDescriptor(forProperty: name))
- }
- public mutating func setValue(value: Any, forProperty name: String) throws {
- try setValue(value, using: try Self.unsafeDescriptor(forProperty: name))
- }
- }
- func callSite() {
- let myObject = ReflectableClass()
- /// Unsafe shorthand
- let description: Any = try! myObject.getValue(forProperty: "description")
- /// Typed version.
- let descriptor = try! SomethingReflectable.descriptor<String>(forProperty: "descriptor")
- let description2: String = myObject.getValue(using: descriptor)
- let myValue = ReflectableStruct()
- /// BAMM!
- try! myValue.setValue("Testing", forProperty: "message") /// compiler warning: cannot mutate `myValue`.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement