Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function or a type method?

Tags:

ios

swift

I want to create a Helper.swift file to add some functions/methods that are useful in different parts of my app.

I was wondering what is the best practice (if there is one): create a class and only create type methods or just create functions?

like image 239
Nico Avatar asked Aug 06 '15 06:08

Nico


People also ask

Should I use method or function?

Here's a simple rule of thumb: if the code acts upon a single instance of an object, use a method. Even better: use a method unless there is a compelling reason to write it as a function.

Is a method a type of function?

A method, like a function, is a set of instructions that perform a task. The difference is that a method is associated with an object, while a function is not.

Whats the difference between a function and a method?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.

Is it called method or function?

Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again.


1 Answers

I would generally lean towards using a type methods on an appropriately named type, in order to give your helper methods context and avoid polluting the global namespace.

In Swift, structs are an ideal candidate for this sort of construct:

struct Helper {
    static func helpfulMethod() { ... }
}

I also use embedded structs with static constants quite liberally in my top level types in order to group related constants within my code.

In writing custom Swift types, you should generally consider using structs first, and only resort to classes when inheritance, reference semantics (as opposed to the implicit copying with value semantics) or ownership semantics (unowned/weak) are required. In this case, your utility functions will be stateless, and there is no inheritance to speak of, so a struct should really be preferred over a class.

I would argue that in general, the Swift language is moving away from global functions in favour of the implicit namespacing provided by types (and protocols/generics). But it's still largely a matter of style/personal preference, and for something as simple as a utility function it's of little consequence.

like image 158
Stuart Avatar answered Sep 18 '22 12:09

Stuart