I’m new to IOS Development and I’m unable to figure out how we can define a global method.
I have a function
func getBanners(){} declared in a class.
I want to declare and use it globally.
I’m new to IOS Development and I’m unable to figure out how we can define a global method.
I have a function
func getBanners(){} declared in a class.
I want to declare and use it globally.
2
Answers
you have several options here you could add it on global scope or introduce a class/enum with a static func. I personally would go with the enum, if functionality has to be available in another module, you have to set the access control to public.
Cheers
Sir SwiftAlot ✌️
If you have a function defined in a class
provided you have an instance of the class, you can call it anywhere in the module:
Note that
Foo()
creates an instance ofFoo
and thenbar
is called on that instance.If you want to be able to call the function without an instance, you need to mark it static:
To call it you need to specify the class:
Note that you can no longer access instance variables because the function is associated with the class itself, not a specific instance of the class.
Also, it doesn’t need to be a class. You can also have static functions in
enum
s andstruct
sYou can also have a bare function not declared in a class:
Call it like this
The above is not generally considered good practice, although there are occasions where it is used in the Standard library e.g.
print()
andzip()
To complicate things further, there are keywords to control the visibility of where you can call the function from