3

im new in swift. I'd like to ask u if i go the right way.

I have something like this:

class ViewController: UIViewController {

    struct myVars {
        var static short_text = ""
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        println(short_text)
    }

    func loadData() {
         myVars.short_text = "Hello world!"
    }
}

This code works. I have "Hello world!" string in the variable and i can print it. But iam asking you if this is a good and clear way to redefine static var? I do it because i want to work with this variable across the code.

Thank you for your answers.

PS: The final methods are much more difficult. This is shorted code for example only.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Harry Zephyr
  • 33
  • 1
  • 4
  • thank you! I'm not so good in english to describe it as well as i'd like to do. But simply: I load a lot of data in function loadData and i need to use that data in another functions without calling loadData again. Because data was once loaded. Its better to use internal var and loose struct? – Harry Zephyr Jun 19 '15 at 14:13
  • possible duplicate of [How do you share data between view controllers and other objects in Swift?](http://stackoverflow.com/questions/29734954/how-do-you-share-data-between-view-controllers-and-other-objects-in-swift) – nhgrif Jun 19 '15 at 14:25
  • (a) i mean i use internal var short_text="" and its not inside struct. Thanks for ur help – Harry Zephyr Jun 19 '15 at 14:28

1 Answers1

1

If your intent is to make the variable for this instance of ViewController accessible to other classes (i.e. other view controllers), then you don't have to use static. You only need to use static if it is critical to make the property accessible across multiple instances of that class. I don't think that's what you intended here.

If the intent is to pass data between the view controllers, I'd suggest you refer to:

If you search for "pass data between view controllers", you'll find lots of other similar links.

Bottom line, the use of static is possible, but probably not what you intended.


Two side notes:

  1. You are using a static within a struct. Swift 1.2 obviates the need for that pattern. If you really need static (and I don't think you need it here), you can just declare your variable as static and eliminate the struct:

    static var shortText = ""
    
  2. I don't think your use of struct meant to open the "by-value vs by-reference" discussion, but if you did, I might refer you to WWDC 2015 video Building Better Apps with Value Types in Swift.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044