Skip to content

Instantly share code, notes, and snippets.

@pilky
Created October 28, 2019 14:30
Show Gist options
  • Save pilky/81bf837d25f39b9615b4b3e2b8231c8d to your computer and use it in GitHub Desktop.
Save pilky/81bf837d25f39b9615b4b3e2b8231c8d to your computer and use it in GitHub Desktop.
Optional KeyPath Weirdness
import Cocoa
class Foo {
var string = "test"
var optionalString: String?
}
let foo = Foo()
foo[keyPath: \.string] == nil //false
foo[keyPath: \.optionalString] == nil //true
func value<Object, Type>(of keyPath: ReferenceWritableKeyPath<Object, Type>, for object: Object) -> Any? {
return object[keyPath: keyPath]
}
value(of: \.string, for: foo) == nil // false
value(of: \.optionalString, for: foo) == nil // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment