Reputation: 10355
In the latest version of Swift, is there any way to get all the vars defined by a protocol? Imagine I have something like:
protocol Foo {
var a: Double { get set }
var b: Double { get set }
}
class SomeClass: Foo {
var a: Double = 1
var b: Double = 2
var c: Int = 3
}
I want a way to take a SomeClass
object and know to query against variables a
and b
because those are the two the protocol defines. For example, I may want to sum up the values of all the variables from the protocol. e.g. something like this non-functional code.
let obj = SomeClass()
let paths = Foo.allKeyPaths
let total = paths.reduce(0) { $0 + obj[keyPath: $1] }
In my actual use case the protocol has around 20 variables. I don't want to hardcode an array of keys because somebody might add a new variable to the protocol but forget to update that array, for example. I'm wanting it to be dynamic at runtime.
Upvotes: 1
Views: 558
Reputation: 17060
Unfortunately, this isn't possible in the current version of Swift.
Upvotes: 2