Kiwo Tew
Kiwo Tew

Reputation: 1531

Swift where to place code in viewcontrolles

As a newbie on iOS dev with swift I wanna ask where I should put code in view controllers. If it even matters.

By that I mean, should custom functions() and variables come before the standard eg override functions() ?

Also,

Can I delete:

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

From files that I dont use it in at all?

Upvotes: 3

Views: 428

Answers (3)

Cole
Cole

Reputation: 2646

If you want to add a method that needs override like viewWillAppear than it's as simple as

override func viewWillAppear(animated: Bool) {

}

If you want just a normal function, maybe with a parameter, you can do it like this

func myNewFunction(name: String) {}

This gives me a new function that takes in a string. It can appear at the top scope right next to viewDidLoad, your inits, etc.

My variables go at the top. I put them like so

// MARK: - Outlets
[my Outlets from Storyboard]

// MARK: - Class Properties
[my constants]

[my variables]

// MARK: - Initializers
required init(coder aDecoder: NSCoder {
     super.init(coder: aDecoder)
}

// MARK: - View Handlers
[viewDidLoad and didRecieveMemoryWarning, etc...]

// MARK: - Utility Methods

[all my functions]

[[end of class]]

As for your didRecieveMemoryWarning you can delete it but I recommend you keep in your view controller in case you want to manage memory.

Upvotes: 2

Kelvin Lau
Kelvin Lau

Reputation: 6781

I've learned to put instance variables all the way at the top, but also seen variables that existed below functions. I also grouped override in their own cluster, and grouped my custom functions in another. Extensions is a good way to group a set of functions.

Yes, you can delete didReceiveMemoryWarning since the super implementation will always exist.

Upvotes: 0

Sunkas
Sunkas

Reputation: 9590

Yes, you can delete didReceiveMemoryWarning

Code you want to run when you start a viewcontroller should be placed in

override public func viewDidLoad()
{
    super.viewDidLoad()
    // your code here....
}

It good practice to place instance variables at the top of you class.

Upvotes: 0

Related Questions