I'm trying to build my first spritekit game in swift. I don't understand where to store constants so I can make them available to the whole project. I have some experience with C++ and I used to create a Constants.h file. Is there such thing in Swift? What's the recommended practice to do this?
Right now I'm using a struct with static constants but I'm not sure if it's the right way to do it:
struct Constants {
static let gravity : Int = 20
}
Creating Our App Constant Fileswift into a folder named something like Utils . Make sure to import UIKit . Create the Parent/Root struct that will contain each struct type. You can call it whatever works for you App , Main , Constants , whatever.
Every useful program needs to store data at some point, and in Swift there are two ways to do it: variables and constants. A variable is a data store that can have its value changed whenever you want, and a constant is a data store that you set once and can never change.
Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.
struct Constants {
static let buildName = "Orange-Pie"
struct FacebookConstants {
static let clientId ="asdasdsa"
}
struct TwitterConstants {
static let clientId ="asdasdsa"
}
}
Use :
Constants.FacebookConstants.clientId
If you have highly generic constants needed by every part of your program, this is indicating a design problem (whenever you are at a loss of where something should go, you probably have a design problem). Things like a gravitational constant shouldn't be necessary for the vast majority of the program, so they generally don't need to be global constants (that's true in C++, too).
Put your constants with the thing that needs that constant, or pass them into the thing that needs that constant. SpriteKit should do most gravity calculations for you, but if you're doing additional physics work, then there should be some object that represents the physics engine or "the world." That's where the gravity constant belongs. Alternately, put the gravity constant into a struct that you pass into the physics engine at launch.
Even if you do have very broad need of the gravitational constant, then you should put it into a struct like PhysicalConstants
, not a generic Constants
(which makes code reuse hard because it mixes unrelated things). A common case of this in my code are "style" constants like "the systemwide highlight color" (which are likely to be changed by the client, so I want a single place to modify them). These go into a header called Style.h
in my apps, and now would go into a Style
struct. But they're kept separate from non-style constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With