Reputation: 301
I have been declaring variables both inside and outside a Class as shown below. My understanding of OOP is to limit their scope. However, to use them in other classes/files I put them outside (e.g."testLabel"). Mainly because it "works" and I am not familiar enough with OOP to do otherwise.
var testlabel:UILabel!
public var earth = SKShapeNode(circleOfRadius: 15)
class GameScene: SKScene , SKPhysicsContactDelegate {
var startTime = NSTimeInterval()
var skView:SKView!
My question is: What is best practice in Swift/OOP to make variables available to all classes?
I have read several discussions but still not clear on the dangers (versus convenience) of declaring variables publicly or globally.
Thanks for your help.
Upvotes: 0
Views: 176
Reputation: 1854
The "dangers" of declaring global variables are more like "code smells" or bad practice. They aren't dangerous in that they will cause your code to crash, but they are dangerous in that they cause your code to become more unwieldy and more difficult to maintain, as your classes are not neatly encapsulated, and some of their functionality lives other places.
Sometimes global behavior is necessary, though. In that case, I think you should make a shared instance or singleton of some class that all other classes can reference. Then, instead of having magic floating variables, you at least encapsulate that behavior in one class that is easy to find and control. Apple uses shared instances all over their code.
http://www.raywenderlich.com/86477/introducing-ios-design-patterns-in-swift-part-1
https://thatthinginswift.com/singletons/
Upvotes: 1
Reputation: 399
If you declare a variable outside of a class it becomes Global variable. It's best practice to declare variables with in class if you don't use them in another classes.
I am not sure if there are any dangers if we declare as global variables.
Upvotes: 3