0

I am new to Swift, coming from C and Java background.

I am trying to pass a struct (called 'Player') object from one view controller to another, and as i learned one proper way to do is first defining it in the target VC like:

class TargetVC: UIViewController {

     var playerVar: Player!
}

And then assigning it in prepare function inside source VC:

 if let targetVC = segue.destination as? TargetVC 
    {
        targetVC.playerVar = myPlayer
    }

But i thinked about simply using a global variable to pass the Player object to the target view controller by defining it like:

var myPlayer = Player() // Global Variable

class SourceVC: UIViewController {

}

Then reaching it in target VC:

class TargetVC: UIViewController {

     myPlayer.name =  // Stuff
}

Would this method cause any problems in runtime or does it have any disadvantages? If yes, what are them?

Thanks in advance.

Muhammed Gül
  • 825
  • 10
  • 19
  • 1
    Unmanaged access. Image you have 10 places where you overwrite that variable, as the code grows you will have very little control over who is accessing/changing the variable data – Cerlin Apr 08 '19 at 12:23
  • @CerlinBoss Yes, i think this'd be the most important disadvantage. Thanks. – Muhammed Gül Apr 08 '19 at 12:41

2 Answers2

0

One disadvantage is, as the name suggests, everything has access to global variables, even things that have no reason to see, much less modify, that data.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Passing data gives to you to conform programming principles to build a good classes, even in your example. It makes classes more extendable and reusable in many cases.

Global var gives some advantages to reach needed data, but you have to care about reference cycles, memory managing, handle threads, queues and blocks, etc.

You can also read out about singletones, static vars,... – where you can get some data from class scope vars.

Agisight
  • 1,778
  • 1
  • 14
  • 15
  • Here is some build-in singletone classes and its class-scoped vars in Swift UIKit: `UIScreen.main`, `UserDefaults.standard`, `DispatchQueue.main`, etc. Study of singletone technology will be very useful for beginners. – Agisight Apr 08 '19 at 12:53
  • 'It makes classes more extendable and reusable in many cases.' Why? 'but you have to care about reference cycles, memory managing, handle threads, queues and blocks, etc.' ??? Doesn't that apply when using dependency injection? – J. Doe Apr 08 '19 at 12:55
  • Good classes tries to avoid using globals to be useful with other parameters. You can use it together or pass your services to the class. One does not interfere with the other. – Agisight Apr 08 '19 at 13:18