Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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.

like image 734
MiguelSlv Avatar asked Sep 14 '14 13:09

MiguelSlv


1 Answers

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;
    }
} 
like image 196
codester Avatar answered Nov 15 '22 08:11

codester