Optional properties on key paths

I have a model type and a view type. The view type reads some values from the model using key paths:

struct Model {
    var name: String?
}

struct View {
    var caption: String?
    func bind<T>(path: WritableKeyPath<View, T>, to modelPath: KeyPath<Model, T>) {
        // then later assign to `self[keyPath: path]` using `model[keyPath: modelPath]`
    }
}

let view = View()
view.bind(path: \.caption, to: \.name)

This works, but only as long as the name property on the Model is optional. Which is a pity, wouldn’t it make sense for a value at KeyPath<Foo, T> to be assignable to WritableKeyPath<Foo, T?>, kind of how it works with plain values?

var string: String?
let s: String = "foo"
string = s

Or:

func foo(_ s: String?) {}
let s: String = "foo"
foo(s)

Or even:

func foo<T>(_ s: T?) {}
let s: String = "foo"
foo(s)

Hm, I see, this doesn’t really make sense. It’s not the assignment that’s the problem, it’s the bind method signature, where we can’t really conflate T with T?. Gosh I wish it were possible to delete my own topics in Discourse!

Closing by request of the thread’s only participant.

2 Likes