[swift-evolution] Swift's 'observe()' doesn't work for key paths with optionals?

Brent Royal-Gordon brent at architechies.com
Sat Jul 22 02:41:39 CDT 2017


> On Jul 22, 2017, at 12:12 AM, William Shipley via swift-evolution <swift-evolution at swift.org> wrote:
> 
>         submodelObservation = observe(\.controller.submodel) { object, change in
>     // code
>         }
> 
> 
>     @objc dynamic internal var controller: Controller?
> 
> in the the “Controller" class:
> 
>     @objc dynamic internal var submodel: SubmodelForImporting?


I believe you're meant to actually construct a key path which looks through an `Optional` like this:

	\.controller?.submodel

But if you try that, you'll get a different, temporary error:

	error: key path support for optional chaining components is not implemented

My understanding is that optional chaining in key paths *is* planned for Swift 4; it just hasn't landed yet. If making `controller` an implicitly-unwrapped optional would be a suitable workaround for you, I see that a couple pull requests to support IUOs were merged to swift-4.0-branch recently[1]; they might be in the open-source Swift 4 snapshot[2]. If not, my best suggestion would be to temporarily add a computed `controller_submodel` property and use the traditional `keyPathsForValuesAffecting…` mechanism to tie it to the underlying properties.

	[1] https://github.com/apple/swift/pull/11005
	[2] https://swift.org/download/#snapshots

-- 
Brent Royal-Gordon
Architechies

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170722/b278afbf/attachment.html>


More information about the swift-evolution mailing list