Tajnero
Tajnero

Reputation: 593

Using global constants in Swift

While programming in Java there is common solution for cleaner code when we use static constants like this:

public class Game {
    private static final int MAX_PLAYERS_NUMBER = 1000;
}

I like very much this approach and I wanted to cast it somehow to Swift. So I started from static constants:

class Game {
    static let maxPlayersNumber = 1000
}

It looks good, but it's weird in code when I always have to use class name in non-static methods:

func doSomething() {
    print(Game.maxPlayersNumber)
}

So I thought about two approaches, one is just simple property in class:

class Game {
    let maxPlayersNumber = 1000
}

And second is use global constant in file:

let maxPlayersNumber = 1000

class Game {}

Still I'm not sure what is the best solution for using constants in methods.

Upvotes: 0

Views: 4131

Answers (2)

Nikunj Damani
Nikunj Damani

Reputation: 753

If you want to define global constant across the project you should use struct rather then class as Apple suggested.

struct AppConstant {
    static let constant1 = 100
}

If you want constant across the class you should just define a property with let as you have defined at last.

 class Game {

    let maxPlayersNumber = 1000

    func doSomething() {
      print(maxPlayersNumber)
    }
 }

Upvotes: 3

Bhagyalaxmi Poojary
Bhagyalaxmi Poojary

Reputation: 1213

You may create a new file inheriting from NSObject and declare the constants in this file as below:

public static let maxPlayersNumber = 1000

here, maxPlayersNumber can be accessed throughout your project scope in the following way :

Constants. maxPlayersNumber 

where Constants is the name of the file and maxPlayersNumber is the constant declared in the file.

Upvotes: -1

Related Questions