Swift Singleton

Hello friends, in this article, we will talk about what Singleton is and how to use it with Swift.

This pattern is very commonly used to avoid static variables and functions in general. We can easily access and use the structure we have developed with a Util, Manager or Singleton model that you have developed.

In the example we will do for this article, we will create an Authentication Util. The functions that will be in this Util are as follows;

Login with username and password
Sign in with FaceID/TouchID
Log out

There will also be a variable that controls whether the user is logged in or not when the application is opened. We can do page redirection according to this variable.

My design for this example is as follows.

After creating 3 functions and variables for the Authentication Util, I create a static variable in this Util instead of creating separate instances on each page where we will use these functions. This variable; It is generally defined as instance, shared or default. I manage everything related to Authentication from here.

My View Controller, where I call the functions, is as follows.

This way you can use it easily. You can click here to examine the project in detail, and here to read more swift related articles. If you have questions, you can reach us by sending an e-mail or comment. Good work.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.