S.Shahsiah S.Shahsiah - 5 months ago 6
Swift Question

In cocoa swift (programming for osx), where (in which class or function or file) should I write normal functions like "for" or "if"?

I'm new to cocoa and the swift programming language (but I know c++ to some extent). So far I know how to create action for buttons to change the stringValue of Labels, and how to use text boxes, etc. Now I'd like to know where to write some functions like "for" and "if" to use them alongside button action.
Button actions can't be used in applicationDidFinishLaunching, because that runs when the app launches, also I can't use any functions outside it (needs declaration). Should I create a class or an instance of a class? Should I create a (new) view controller? I'm using Xcode 7.2 and OS X 10.10.5.


EDIT: Now that you clarified you want your button to change the value of a string, let me give you some code:

ViewDidLoad() {
    var aString: String = "WOW"

IBAction func changeString {
    aString = "Wow, it changed !"

You can put if statements and for loops almost wherever you want as long as they are in a method.

You can put them in a ViewController file in the ViewDidLoad() method for example that executes each time the VC is loaded.

If you already have a button action (IBAction) that works, you shouldn't need to create another xib file. If you want to use for or if with data that comes in your IBAction, either put them in the IBAction or create vars outside the IBAction (inside ViewDidLoad() for example) that are then modified inside the IBAction.