Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating class for defining constants in swift

Note: I want to achieve similar functionality in swift - Where to store global constants in an iOS application?

I have two classes - MasterViewController and DetailViewController

I want to define an enum (refer below enum) and use its values in both classes:

enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

I tried to define it in MasterViewController and use it in DetailViewController like this:

let aPlanet = Planet.Earth

but compiler is complaining :(

"Use of unresolved identifier Planet"

Generally in my objective c code I used to have a global constant file, which I used to import in app-prefix.pch file, which was making it accessible to all files within my project, but in this case I am clueless.

like image 714
Devarshi Avatar asked Aug 08 '14 04:08

Devarshi


People also ask

How do you set constants in Swift?

To declare a constant, you use the let keyword. Take a look at the following example in which we declare street as a constant instead of a variable. If we only update the first line, replacing var with let , Xcode throws an error for obvious reasons. Trying to change the value of a constant is not allowed in Swift.

Can we define class as constant?

Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

Which keyword must be used to create constants in Swift?

In the previous episode of Swift Fundamentals, we briefly talked about variables and constants. You learned that the var keyword declares a variable and the let keyword declares a constant. Variables and constants both store values that can be referenced by a name.


2 Answers

If your enum is being defined in a class like this:

class MyClass {
    enum Planet: Int {
        // ...
    }
}

You have to access it through your class:

var aPlanet = MyClass.Planet.Earth

You also want to use the rawValue property. You will need that to access the actual Int value:

var aPlanet = MyClass.Planet.Earth.rawValue
like image 93
drewag Avatar answered Oct 31 '22 04:10

drewag


In swift you can declare an enum, variable or function outside of any class or function and it will be available in all your classes (globally)(without the need to import a specific file).

like image 20
Atomix Avatar answered Oct 31 '22 05:10

Atomix