Dynamic member lookup (via marker protocol)

This commit is contained in:
Ilya Puchka
2018-09-22 16:04:57 +01:00
committed by David Jennes
parent 203510175f
commit 7247d0a83d
3 changed files with 47 additions and 1 deletions

View File

@@ -0,0 +1,15 @@
/// Marker protocol so we can know which types support `@dynamicMemberLookup`. Add this to your own types that support
/// lookup by String.
public protocol DynamicMemberLookup {
/// Get a value for a given `String` key
subscript(dynamicMember member: String) -> Any? { get }
}
public extension DynamicMemberLookup where Self: RawRepresentable {
subscript(dynamicMember member: String) -> Any? {
switch member {
case "rawValue": return rawValue
default: return nil
}
}
}

View File

@@ -110,6 +110,8 @@ public struct Variable: Equatable, Resolvable {
return object.value(forKey: bit)
}
#endif
} else if let value = context as? DynamicMemberLookup {
return value[dynamicMember: bit]
} else if let value = context {
return Mirror(reflecting: value).getValue(for: bit)
}