Swift - how to access public constants without having to run a class, as in C #

You do not need to instantiate a class to access a public constant. I recently started working in Swift, so I have to skip something here.

In this simple example:

public class MyConstants{ public let constX=1; } public class Consumer{ func foo(){ var x = MyConstants.constX;// Compiler error: MyConstants don't have constX } } 

This foo code gives a compilation error. To work, I need to create an instance of MyConstants as follows:

 public class Consumer{ func foo(){ var dummy = MyConstants(); var x = dummy.constX; } } 

Adding static to constX is not allowed.

+5
source share
5 answers

Use struct with static types. struct more appropriate since in enum you can only bind one type of associative value, but you can contain a "Property of type of any type" in both.

 public struct MyConstants{ static let constX=1; } public class Consumer{ func foo(){ var x = MyConstants.constX; } } 
+16
source

You must use immutable static variables. Unfortunately, classes only support computed properties using the class modifier โ€” the compiler throws an error indicating that class variables are not yet supported.

But in structures, you can create static data members:

 struct Constants { static let myConstant = 5 } 

and, of course, you do not need to instantiate, since an immutable static property can simply be obtained as:

 Constants.myConstant 
+5
source

If you want a constant, you can also "fake" the asup yet-unsupported class variable with the property computed by the class:

 public class MyConstants{ public class var constX: Int { return 1 }; } public class Consumer{ func foo(){ var x = MyConstants.constX; // Now works fine. } } 
+2
source

For string constants, I make a bunch of constants in the responsible class file as follows:

 public enum NotificationMessage: String { case kTimerNotificationId = "NotificationIdentifier" } 

Then, to use it from anywhere else in the code, simply:

 println("\(NotificationMessage.kTimerNotificationId.rawValue)") 

Do not forget .rawValue.

+1
source

I found a solution below, but hope someone can clarify or post a better solution

 enum MyConstantsV2 { static var constX = 1 } public class Consumerv2{ func foo(){ var x = MyConstantsV2.constX; } } 
0
source

Source: https://habr.com/ru/post/1202534/


All Articles