简体   繁体   中英

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.

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)
    }
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM