Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metaprogramming in Swift

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?

like image 746
Yaron Tausky Avatar asked Nov 14 '14 21:11

Yaron Tausky


1 Answers

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.

like image 112
Mike S Avatar answered Sep 20 '22 13:09

Mike S