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

So how do you define common class constants in Swift?

Problem

For a β€œnormal” class, you can define them as follows:

class C { static let k = 1 } let a = Ck // 1 

But if you do the same in a generic class:

 class C<T> { static let k = 1 } 

You get the following compilation error:

Static stored properties are not yet supported in generic types

So how to solve this?

My current solution

I am now using struct to solve this problem:

 struct CConstant { static let K = 1 } 

It is not defined in the realm of the general 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 consider it necessary =)

+5
source share
2 answers

You can define a global constant with the access level fileprivate or private in the same .swift file where your common class is defined. Thus, it will not be visible outside this file and will not pollute the global (modular) namespace.

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

Learn more about access levels in Swift 3 .

+2
source

For trivial constants with a typed value, you can simply implement a read-only static computed property:

 class C<T> { // will be evaluated every time the static property is accessed, // therefore not suited for non-trivial constants. static var k : Int { return 1 } } let a = C<()>.k // Access k on C<Void> 

It makes sense not to pollute the "global namespace" since it is a static member on C<T> . Although, unfortunately, you need to specify a general parameter in order to use a constant - since you cannot refer to the type of a universal class without a general parameter (since anything in the static area may require its definition).

For non-trivial constants, you can define a private global constant and use a read-only static computed property in your general class to expose it in the outside world:

 private let _k = SomeClass() class C<T> { static var k : SomeClass { return _k } } 

Again, this allows you to access it as a static member on C<T> without polluting the "global namespace" (although not outside the Swift file that you define it).

+1
source

All Articles