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.

//
//  AuthenticationUtil.swift
//  singleton
//
//  Created by Ömer Sezer on 27.02.2022.
//

import Foundation

class AuthenticationUtil {
    
    static let shared = AuthenticationUtil()
    
    var isLoggedIn = false
    
    func loginWithUsername(username: String, password: String) {
        print("login successful")
    }
    
    func loginWithFaceId() {
        print("login successful")
    }
    
    func logout() {
        print("logout")
    }
}

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

//
//  LoginViewController.swift
//  singleton
//
//  Created by Ömer Sezer on 27.02.2022.
//

import UIKit

class LoginViewController: UIViewController {

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

    @IBAction func onButtonLoginWithUsernameClicked(_ sender: Any) {
        AuthenticationUtil.shared.loginWithUsername(username: "test username", password: "test password")
    }
    
    @IBAction func onButtonLoginWithFaceIdClicked(_ sender: Any) {
        AuthenticationUtil.shared.loginWithFaceId()
    }
    
    @IBAction func onButtonLogoutClicked(_ sender: Any) {
        AuthenticationUtil.shared.logout()
    }
}

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 Reply

Your email address will not be published. Required fields are marked *

Press ESC to close