Coming from C++, I'm trying to do some metaprogramming in Swift. For example, I'd like to implement a metafunction that adds two numbers. I've tried something like this:
protocol IntWrapper {
class var value: Int { get }
}
struct A: IntWrapper {
static let value = 5
}
struct B: IntWrapper {
static let value = 7
}
struct Sum<T: IntWrapper, U: IntWrapper>: IntWrapper {
static let value = T.value + U.value
}
This, however, doesn't work: Xcode complains that T.Type
doesn't have a member value
(or just crashes, sometimes.)
How can implement such functionality?
static
stored properties are not (currently) supported on generic objects. When I put your code in a playground, I actually get this error:
Playground execution failed: <EXPR>:23:5: error: static variables not yet supported in generic types
static let value = T.value + U.value
^~~~~~
You can get around that by using a computed property instead (which may have been what you wanted in the first place anyway):
struct Sum<T: IntWrapper, U: IntWrapper>: IntWrapper {
static var value: Int {
return T.value + U.value
}
}
Note: Since it's a computed property, you need to declare value
with var
and not let
.
With those changes, println(Sum<A, B>.value)
prints 12
like you'd expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With