ghashi ghashi - 1 month ago 4x
Swift Question

How to define static constant in a generic class in swift?

So how do you define generic class constants in Swift?

The problem

For a "normal" class you can define them like this:

class C {
static let k = 1

let a = C.k // 1

But if you do the same on a generic class:

class C<T> {
static let k = 1

You get the following error on compilation:

Static stored properties not yet supported in generic types

So how to solve this?

My current solution

Right now, I'm using
to solve this:

struct CConstant {
static let K = 1

This is not defined in the scope of the generic class but it works for me. Do you have a better solution?


ps: this is my first question here, so please help me improve this question if you think it is necessary =)


You can define global constant with fileprivate or private access level in the same .swift file where your generic class is defined. So it will not be visible outside of this file and will not pollute global (module) namespace.

If you need to access this constant from outside of current file then declare it as internal (default access level) or public and name it like ClassConstant so it will be obvious that it relates to Class.

Read more about access levels in Swift 3.