Search code examples
iosswiftcocoa-touchcoding-styleconstants

What is the best approach to create Constant file in Swift? Please check the description


I have seen some people declaring constant file using Struct like this:

Approach 1:

struct Constants {
    struct UserInfoParam {
        static let userName = "user_name"
        static let userID = "user_id"
    }
}

And call it like this:

print(Constants.UserInfoParam.userName)

Approach 2: And some people directly create a Swift file and simply declare the variables, like:

import Foundation

let userName = "user_name"
let userID = "user_id"

And call it simply like this:

print(userID)

I want to know which approach is best to implement for Code Quality and Other Coding aspects. Can someone clarify me this? Thanks in Advance.


Solution

  • Coding style depends on person to person, so here it also depends on you and your requirement.

    For example with Approach 1, you can categorize your constants. Check,

    struct Constants {
        struct UserInfoParam {
            static let userName = "user_name"
            static let userID = "user_id"
        }
    
        struct API {
            static let api1 = "api1"
            static let api2 = "api2"
        }
    
        struct AlertMessages {
            static let NoDataFound = "No Data Found."
            static let InternetError = "Check internet connection."
        }
    
    }
    

    In the above approach, personally I prefer not to use Constants struct, as it just increasing the struct hierarchy.

    So I did like this,

    struct UserInfoParam {
        :
    }
    
    struct API {
        :
    }
    
    struct AlertMessages {
        :
    }
    

    Now whenever need I just write AlertMessages.NoDataFound instead of Constants.AlertMessages.NoDataFound. These both way are correct and you can try anyone.

    But when you talked about Approach2, then you can use it for some general constants.

    For Eg.

    let Base_URL = "Base URL"
    let ItunesAppId = "ID"
    

    so on.

    These objects globally used, even in the Constants struct too. These vars are not belonging to any category.

    In these ways generally developer did code.