0

I have a struct that contains an optional value innerData. Unfortunately, whenever I try to change its value using WritableKeyPath, it gives me the error

struct MyData {
  struct Foo {
    var name: String?
  }
  var innerData: Foo? = Foo()
}


final class MyClass {
  var data = MyData()

  func update<T>(
    _ keyPath: WritableKeyPath<MyData, T>,
    to value: T
  ) {
    data[keyPath: keyPath] = value
  }
}


let myClass = MyClass()
print(myClass.data.innerData?.name)

myClass.update(\.innerData?.name, to: "hi") // Error here

print(myClass.data.innerData?.name)

Unfortunately, whenever I try to change its value using WritableKeyPath, it gives me the error:

Key path value type 'WritableKeyPath<MyData, String?>' cannot be converted to contextual type 'KeyPath<MyData, String?>'

I can fix this by force unwrapping innerData, but I don't want to do that. Is there a way around this?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Probably a duplicate of https://stackoverflow.com/questions/59637100/how-does-swift-referencewritablekeypath-work-with-an-optional-property See if the answer there helps you. – matt May 04 '22 at 13:15
  • I saw that but it didn’t help unfortunately – Tometoyou May 04 '22 at 13:24

0 Answers0