

{"id":118605,"date":"2023-10-07T19:00:15","date_gmt":"2023-10-07T13:30:15","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=118605"},"modified":"2023-10-07T19:08:48","modified_gmt":"2023-10-07T13:38:48","slug":"swift-constants","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/swift-constants\/","title":{"rendered":"Swift Constants"},"content":{"rendered":"<p>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.<\/p>\n<p>In this article, we will learn about constants, their usage, and relevant examples to understand them.<\/p>\n<h2>Declaration &amp; Assign Values<\/h2>\n<p>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&#8217;s execution.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let isConstant: \t\/\/Declaring a constant\r\nlet year = 2023\t\/\/ Declaring and assigning a value to constant\r\n<\/pre>\n<h3>Type Annotations<\/h3>\n<p>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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let example: String = \"DataFlair\"\r\n<\/pre>\n<h3>Type Inference<\/h3>\n<p>Type inference helps us deduce a constant&#8217;s data type based on its initial value. We can omit the type annotation during declaration, and Swift will infer the type for us.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let year = 2023\r\n<\/pre>\n<p>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.<\/p>\n<h3>Naming Constants<\/h3>\n<ul>\n<li>It should begin with an alphabet (A-Z or a-z) or underscore (_).<\/li>\n<li>It may contain letters or numbers or underscore.<\/li>\n<li>Other symbols or characters like !, @, #, etc are not allowed.<\/li>\n<li>Swift is a case-sensitive language. So, dataFlair, and DataFlair are different.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ valid constants\r\nlet DataFlair\r\nlet dataFlair\r\nlet _dataFlair\r\n\r\n\/\/Invalid constants\r\nlet 1dataFlair \r\nlet DataFlair#\r\nlet _DataFlair@\r\n<\/pre>\n<h3>Printing Constants<\/h3>\n<p>We print constants to display information to users. We do it by using the &#8220;print&#8221; function or string interpolation.<\/p>\n<h4>For instance:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let name: String = \"DataFlair\"\r\nprint(name)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>DataFlair<\/p>\n<p>We can also embed constants directly within a string using string interpolation. It becomes easy to format and display variable values alongside text.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let name: String = \"DataFlair\"\r\nprint( \"Name: \\(name)\")\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Name: DataFlair<\/p>\n<h3>Global Constants<\/h3>\n<p>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.<\/p>\n<h4>Case-less Enums<\/h4>\n<p>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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">enum ColorConstants {\r\n    static let primary = \"Blue\"\r\n    static let secondary = \"Red\"\r\n}\r\n\r\nprint(ColorConstants.primary)\r\nprint(ColorConstants.secondary)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Blue<br \/>\nRed<\/p>\n<h4>Structs<\/h4>\n<p>We use structs to group related constants. For example, we can group the constants like appName, appVersion, and its appDefaultTheme using a struct appDetails.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">struct appDetails {\r\n    static let appName = \"DataFlair\"\r\n    static let appVersion = \"1.0.0\"\r\n    static let appDefaultTheme = \"light\"\r\n}\r\n\r\nprint(appDetails.appName)\r\nprint(appDetails.appVersion)\r\nprint(appDetails.appDefaultTheme)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>DataFlair<br \/>\n1.0.0<br \/>\nlight<\/p>\n<h4>Extensions<\/h4>\n<p>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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">extension String {\r\n    func addExclamation() -&gt; String{\r\n        return self + \"!\"\r\n    }\r\n}\r\n\r\nlet message = \"Hi from DataFlair\"\r\nprint(message)\r\nlet extensionExample = message.addExclamation()\r\n\r\nprint(extensionExample)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hi from DataFlair<br \/>\nHi from DataFlair!<\/p>\n<h3>Conclusion<\/h3>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":118607,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27789],"tags":[28288,28282],"class_list":["post-118605","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift-tutorials","tag-swift-constants","tag-swift-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Swift Constants - DataFlair<\/title>\n<meta name=\"description\" content=\"Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/swift-constants\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Constants - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/swift-constants\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-07T13:30:15+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-10-07T13:38:48+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift Constants - DataFlair","description":"Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/swift-constants\/","og_locale":"en_US","og_type":"article","og_title":"Swift Constants - DataFlair","og_description":"Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them.","og_url":"https:\/\/data-flair.training\/blogs\/swift-constants\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-10-07T13:30:15+00:00","article_modified_time":"2023-10-07T13:38:48+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Swift Constants","datePublished":"2023-10-07T13:30:15+00:00","dateModified":"2023-10-07T13:38:48+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/"},"wordCount":526,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp","keywords":["swift constants","swift tutorial"],"articleSection":["Swift Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/swift-constants\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/","url":"https:\/\/data-flair.training\/blogs\/swift-constants\/","name":"Swift Constants - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp","datePublished":"2023-10-07T13:30:15+00:00","dateModified":"2023-10-07T13:38:48+00:00","description":"Swift constants are unchangeable units that hold information throughout a program. Once set, they stay the same, and we cannot alter them.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/swift-constants\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/08\/swift-contants.webp","width":1200,"height":628,"caption":"swift contants"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/swift-constants\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Swift Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/swift-tutorials\/"},{"@type":"ListItem","position":3,"name":"Swift Constants"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/118605","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=118605"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/118605\/revisions"}],"predecessor-version":[{"id":122749,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/118605\/revisions\/122749"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/118607"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=118605"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=118605"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=118605"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}