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
[code lang=”obj-c”]
// Objective-C
#define APP_ALERT_TITLE "Objective-C Constant"
[/code]
Swift has new syntax to define the constant (#define)
[code lang=”obj-c”]
// Swift
let APP_ALERT_TITLE = "Swift Constants"
[/code]

Lets try

Create a swift file with the constants

[code lang=”obj-c”]
import Foundation
class Constants {
// MARK: List of Constants
static let APP_ALERT_TITLE = "Swift Constants"
static let SAMPLE_MESSAGE = "The alert is working !!"
}
[/code]
Note : Here the MARK statement is also changed.
[code lang=”obj-c”]
// Objective-C
#pragma mark –
#pragma mark List of Constants
[/code]
[code lang=”obj-c”]
// Swift
// MARK: List of Constants
[/code]

Use of constant

You don’t need to import any swift file you can directly use like as :
Constants.SAMPLE_MESSAGE
Sample Code :
[code lang=”obj-c”]
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.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() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
[/code]
Happy Coding 🙂