1

I need an array of writable keypaths to edit variables, but the Class is undefined. How could I do something like this ?

var properties: [ WritableKeyPath< AnyClass, Double > ]

properties.append( \Class1.tag )
properties.append( \AnyClass2.volume )

func setPropertie (keyIndex: Int, value : Double) {
    anyObject[keyPath: properties[keyIndex] ] = value
}

In this case, trying to append( \Class1.tag ) got this error: Type 'AnyClass' (aka 'AnyObject.Type') has no member 'threshold'

Fischer
  • 1,513
  • 4
  • 17
  • 38

1 Answers1

1

Your WritableKeyPath<AnyClass,Double> is made to be take AnyClass but you're putting class specific keypaths.

Class1 as AnyClass would lose access to it's tag object.
Similarly AnyClass2 as AnyClass would also lose access to it's volume object.
Hence \Class1.tag and \AnyClass2.volume won't work for a WritableKeyPath<AnyClass,Double>

What you could do instead is:

var properties = [AnyKeyPath]()
properties.append(\Class1.tag)
properties.append(\AnyClass2.volume)
staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
  • anyVar[keyPath: properties[index] ] = 50 ... And now I get this : " Cannot assign to immutable expression of type 'Any?' " – Fischer Mar 20 '18 at 10:07
  • @Fischer Hm... that's now a problem. Read: https://forums.developer.apple.com/thread/80268. You can store `AnyKeyPath`s for reading but when it comes to writing... I am not sure how to do that. I will try nonetheless and get back if I find something. – staticVoidMan Mar 20 '18 at 10:23
  • @Fischer Seems there's already a [question here](https://stackoverflow.com/questions/48427508/how-do-you-convert-an-anykeypath-to-a-writablekeypath) regarding your next hurdle but it's unanswered so far. – staticVoidMan Mar 20 '18 at 10:26
  • @Fischer so any progress here? how would you later on know which `keyIndex` will give you the `keyPath` associated to it's respective class? Because I can see this getting pretty messy if you plan to have an array of generic `WritableKeyPath`s; assuming if that were even possible, which it isn't right now. Are you sure you're going down the right `path` (pun)? – staticVoidMan Mar 22 '18 at 19:14
  • Nothing. I decided to change my code switching between indexes provided by tags. Would be better with keyIndex. Now I have more lines of code, but works for me – Fischer Mar 22 '18 at 19:19
  • Any way, this post could help: Take a look to this example ... kp.rootType ... kp.valueType ... https://www.klundberg.com/blog/swift-4-keypaths-and-you/ – Fischer Mar 22 '18 at 19:23
  • @Fischer I have seen this link before and also while trying to find you a solution but I never found it to work. I get `Static member 'rootType' cannot be used on instance of type 'AnyKeyPath'` – staticVoidMan Mar 22 '18 at 19:25