Use of constant (#define) in Swift Language – iOS

Swift Constant Test
Swift Constant Test

In Objective-C we are using a header file to create constant variables like as

// Objective-C
#define APP_ALERT_TITLE "Objective-C Constant"

Swift has new syntax to define the constant (#define)

// Swift
let APP_ALERT_TITLE = "Swift Constants"

Lets try

Create a swift file with the constants

import Foundation

class Constants {
    // MARK: List of Constants
    static let APP_ALERT_TITLE = "Swift Constants"
    static let SAMPLE_MESSAGE = "The alert is working !!"

Note : Here the MARK statement is also changed.

// Objective-C
#pragma mark -
#pragma mark List of Constants
// Swift
// MARK: List of Constants

Use of constant

You don’t need to import any swift file you can directly use like as :


Sample Code :

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        print("This is a constant : \(Constants.SAMPLE_MESSAGE)")
        let alert = UIAlertController(title: Constants.APP_ALERT_TITLE, message: Constants.SAMPLE_MESSAGE, preferredStyle: UIAlertControllerStyle.Alert)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.presentViewController(alert, animated: true, completion: nil)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil))

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Happy Coding 🙂