Is there a way in Swift 4.2 to tell if an arbitrary object supports dynamic member lookup?
Something like the example below.
func getName(of object: AnyObject) -> String? {
if let object = object as? DynamicMemberLookupProtocol {
return object["name"]
}
return nil
}
I do not think this is possible at the moment.
However, after SR-8077 Compile error when using @dynamicMemberLookup as a protocol requirement bug gets fixed in a production version of swift (hopefully, in swift 5), we can have a workaround for that in the form of protocols, constrained by @dynamicMemberLookup
.
You can also read here on why @dynamicMemberLookup
was not implemented as a protocol:
We started with the approach of making this be a protocol that types conform to to get this behavior. It turns out that this behavior is very non-protocol like: it is not useful to define generic algorithms over, and existential values are only useful if they define a specific subscript that implements the requirements implicit in this attribute.
For these and other reasons, defining this as a protocol doesn't really fit into the design of Swift.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加