Swift Constants
Interactive Online Courses: Elevate Skills & Succeed Enroll Now!
Constants store data that should not change during the execution of a program. They provide a way to create immutable data. It means that we cannot change the value after initialization. It prevents accidental modifications to data that should remain unchanged.
In this article, we will learn about constants, their usage, and relevant examples to understand them.
Declaration & Assign Values
We declare a constant using the let keyword, followed by the name of the constant, the assignment operator (=), and its initial value. Once assigned, we cannot modify the value of the constant throughout the program’s execution.
let isConstant: //Declaring a constant let year = 2023 // Declaring and assigning a value to constant
Type Annotations
Type annotations allow us to specify the data type of a constant. This feature enhances code clarity. It helps catch type-related errors during compile-time. It also aids in better code documentation. The syntax for type annotation involves using a colon (:) followed by the desired data type.
let example: String = "DataFlair"
Type Inference
Type inference helps us deduce a constant’s data type based on its initial value. We can omit the type annotation during declaration, and Swift will infer the type for us.
let year = 2023
For instance, in the above example, Swift will deduce the data type of the constant year. It will infer the constant year is of Int data type.
Naming Constants
- It should begin with an alphabet (A-Z or a-z) or underscore (_).
- It may contain letters or numbers or underscore.
- Other symbols or characters like !, @, #, etc are not allowed.
- Swift is a case-sensitive language. So, dataFlair, and DataFlair are different.
// valid constants let DataFlair let dataFlair let _dataFlair //Invalid constants let 1dataFlair let DataFlair# let _DataFlair@
Printing Constants
We print constants to display information to users. We do it by using the “print” function or string interpolation.
For instance:
let name: String = "DataFlair" print(name)
Output:
DataFlair
We can also embed constants directly within a string using string interpolation. It becomes easy to format and display variable values alongside text.
let name: String = "DataFlair" print( "Name: \(name)")
Output:
Name: DataFlair
Global Constants
Global constants are defined for a global scope. They remain the same throughout the program. We can use case-less enums, structs, or extensions when global constants are being used at multiple places.
Case-less Enums
Case-less enums in Swift define a set of related static properties into a group of constants under a common namespace. If we have multiple related constants, we can define them under a common name using this. For example, the enum ColorConstants acts as a common name for primary and secondary constants.
enum ColorConstants {
static let primary = "Blue"
static let secondary = "Red"
}
print(ColorConstants.primary)
print(ColorConstants.secondary)
Output:
Blue
Red
Structs
We use structs to group related constants. For example, we can group the constants like appName, appVersion, and its appDefaultTheme using a struct appDetails.
struct appDetails {
static let appName = "DataFlair"
static let appVersion = "1.0.0"
static let appDefaultTheme = "light"
}
print(appDetails.appName)
print(appDetails.appVersion)
print(appDetails.appDefaultTheme)
Output:
DataFlair
1.0.0
light
Extensions
Extensions in Swift are used to extend the capabilities of existing types like structs, enums, or classes. The original implementation of the type remains the same. It just adds new functionality to these types.
extension String {
func addExclamation() -> String{
return self + "!"
}
}
let message = "Hi from DataFlair"
print(message)
let extensionExample = message.addExclamation()
print(extensionExample)
Output:
Hi from DataFlair
Hi from DataFlair!
Conclusion
Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them. They have clear names and follow specific rules. We can easily show their values using the print function or by embedding them in text. Using Swift constants effectively, we can create stable and reliable applications, ensuring that critical data remains safe and consistent.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

