Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Are global functions bad practice? [closed]

I've read that global variables are bad. But, what about global functions? Say I add to my iPhone app project a file called Globals.swift containing func foo() { print("foo") }. Isn't that bad because it could conflict with other global functions of the same name & signature? By the same argument, isn't it bad to use extensions to add new methods to existing types?

like image 980
ma11hew28 Avatar asked Feb 08 '23 22:02

ma11hew28


1 Answers

Global functions are global in lexical scope, but not in visibility. So you don't need to worry about conflicts, really. Global lexical scope means they aren't a member of a type (class, struct, protocol or enum), nor are they specific to locally scoped code such as another function's body.

But that's not the same as global visibility, in multiple ways.

If you define a top-level (aka global) func foo() in an module (app or framework) named MyTarget, the fully namespaced signature of that function is MyTarget.foo(). Even if the Swift standard library were to declare a global func foo(), yours would not necessarily conflict. (However, any call sites would become ambiguous, so you'd have to use the module name to distinguish between MyTarget.foo() and Swift.foo().)

If your code is in a module to be used by other code (e.g. a framework shared between iOS app and extension targets), your func foo() declaration is internal to that module. So, other code importing your module can declare its own func foo(), and call it with just foo(), regardless of whether your function exists. It only has an effect on modules importing yours if it's declared as public func foo(). (And even then, callers can disambiguate using the module name, as above.) Furthermore, you can choose to declare your function as private to the Swift file in which it's defined, in which case it's global in lexical scope but restricted to use only by other code in that file.

Type extensions follow the same reasoning — your extensions are by default internal to the module that creates them, and in its namespace, so there's little risk of conflict.

As for whether it's good program design to use free functions instead of types with methods, that's a hotly debated matter of opinion...

like image 76
rickster Avatar answered Feb 10 '23 12:02

rickster