How to define global constant in swift?

According to normal string in iOS, There is not provide the facility of colorful string in iOS, but have a class NSAttributeString which have provide color of string facility. For formatting a part of a string, you need an attributed string which specifies parts of the string formatted in different ways. In this lesson we’ll learn how to work in attributed strings in Swift.

 First of all you Setup new project, and take different label in the View Controller. Here I am taking six label and all label connects IBOutlet in ViewController.swift file.

One variable is used too many time in the project file, then that types of variable is define as global. Some constant also define as global. here some of example to define constant. one make constant.swift file in your swift project,

Follow the steps to define global constant

go to project > New file > Make one constant file name as : Constant.swift.

define one Struct inside the Constant file, Struct which allow Structured data type and also provide storage of data. Struct define as below.
struct GlobalConstants {
  // Constant define here.

Adding constant inside the define  GlobalConstants,  Here define the all color constant as below.
struct GlobalConstants {
        //  COLOR CONSTANT

        static let kColor_Seperator: UIColor = UIColor(red: 53.0/255.0, green: 126.0/255.0, blue: 167.0/255.0, alpha: 1.0)
        static let kColor_orange: UIColor = UIColor(red: 255.0/255.0, green: 147.0/255.0, blue: 38.0/255.0, alpha: 1.0)
        static let kColor_NonCompliant: UIColor = UIColor(red: 190.0/255.0, green: 15.0/255.0, blue: 52.0/255.0, alpha: 1.0)

You can also adding more constant definition like constant variable, Device, etc,
 struct GlobalConstants {
        //  Device IPHONE
        static let kIphone_4s : Bool =  (UIScreen.mainScreen().bounds.size.height == 480)
        static let kIphone_5 : Bool =  (UIScreen.mainScreen().bounds.size.height == 568)
        static let kIphone_6 : Bool =  (UIScreen.mainScreen().bounds.size.height == 667)
        static let kIphone_6_Plus : Bool =  (UIScreen.mainScreen().bounds.size.height == 736)

    //   Constant Variable.
        static let kBirthDate                     =    "DateOfBirth"
        static let kFirstName                     =    "FirstName"
        static let kLastName                      =    "LastName"

Now you can use this constant in your swift file as below. go to your swift file Name like ViewController.swift, inside viewDidLoad get the color defined constant color and set also of view.
self.view.backgroundColor = Constant.GlobalConstants.kColor_orange
By using this code you set color of the background of view,


How to define global constant in swift? How to define global constant in swift? Reviewed by Kirit Modi on 00:55:00 Rating: 5

No comments:

Powered by Blogger.