MiguelSlv
MiguelSlv

Reputation: 15193

swift - how to access public constants without having to instanciate class, as in C#

Should not be needed create an instance of a class to access a public constant. I recently started working in Swift, so I must be missing 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 an compile error. To work, I need to create an instance of the MyConstants like this:

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

Adding static to constX is not allowed.

Upvotes: 6

Views: 10019

Answers (5)

For string constants what I do is put the bunch of constants into responsible class file in the following way:

public enum NotificationMessage: String {

    case kTimerNotificationId = "NotificationIdentifier"
}

Then for use it from any other point of the code just:

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

Do not forget .rawValue.

Upvotes: 1

Matt Gibson
Matt Gibson

Reputation: 38238

If you want a constant, you can also "fake" the as-yet-unsupported class variable with a class computed property, which does currently work:

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

Upvotes: 2

codester
codester

Reputation: 37189

Use struct with static types.structare more appropriate as in enum you can only bind one type of associative values but you can contain the "Type Property of any type" in both.

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

Upvotes: 19

Antonio
Antonio

Reputation: 72810

You should use immutable static variables. Unfortunately classes support computed properties only with the class modifier - the compiler outputs an error stating that class variables are not yet supported.

But in structs it's possible to create static data members:

struct Constants {
    static let myConstant = 5
}

and of course it's not required to create an instance, as the immutable static property can simply be accessed as:

Constants.myConstant

Upvotes: 7

MiguelSlv
MiguelSlv

Reputation: 15193

I found out the 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;
    }
}

Upvotes: 0

Related Questions