using a function argument as a dynamic variable

You can probably use KeyPath if you only want to access the value:

func canThisWork(with arg: KeyPath<Fuzzy, String?>) {
    print(fuzz[keyPath: arg]!)
}

Or WritableKeyPath if you also want to mutate it:

var fuzz = Fuzzy()

func canThisWork(with arg: WritableKeyPath<Fuzzy, String?>) {
    fuzz[keyPath: arg] = "hi :)"
    print(fuzz[keyPath: arg]!)
}

In both cases you call your function like this:

canThisWork(with: \.hello)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top