[swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types
BJ Homer
bjhomer at gmail.com
Tue Dec 5 14:53:47 CST 2017
> On Dec 5, 2017, at 12:13 PM, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
>
> let result = dynamic x.foo.bar // will crash if foo or bar are not present
>
> let result = dynamic? x.foo.bar // will return nil if foo or bar are not present
Under the proposal given here, the compiler doesn’t know what will happen when “foo” or “bar” are not present. This proposal does not even require the implementation to report if a member is present or not, and there is certainly no guarantee of a crash in such a case. The only thing the compiler knows is that subscript(dynamicMember:) will be called.
Consider the following implementation:
struct PyVal: DynamicMemberLookupProtocol {
subscript(dynamicMember: String) -> PyVal? {
if let pythonMember = python_c_api.get(dynamicMember) {
return PyVal(pythonMember)
}
else {
return nil
}
}
}
let result = x.foo?.bar
There is no crashing here; result will be an optional type, and will be nil if the requested property does not exist. Some other use of DynamicMemberLookupProtocol might accept any value, and just log it to a file! In that case, neither crashing nor returning an optional is required.
-BJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171205/2953d420/attachment.html>
More information about the swift-evolution
mailing list