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)