

{"id":117658,"date":"2023-10-05T19:00:59","date_gmt":"2023-10-05T13:30:59","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=117658"},"modified":"2023-10-05T19:07:02","modified_gmt":"2023-10-05T13:37:02","slug":"swift-variables","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/swift-variables\/","title":{"rendered":"Swift Variables"},"content":{"rendered":"<p>Variables store and manage data during program execution. They act as placeholders.<\/p>\n<p>A variable can hold different types of values, such as numbers, text, or collections. It allows us to manipulate data, perform calculations, and make decisions based on the stored information. In this article, we\u2019ll dive into how we use it and important points to consider while using them.<\/p>\n<h2>Declaration<\/h2>\n<p>Variables are declared using the var keyword, followed by their name and data type. Following is the syntax to declare a variable in Swift.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var variableName: dataType\r\n<\/pre>\n<p>Swift is a statically typed language. This means the data type of a variable is explicitly defined. We cannot change it after its declaration.<\/p>\n<h3>Initialization and reassignment of values<\/h3>\n<p>To store a value in a variable, we need to initialize it. This means we give an initial value to it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var variableExample: String = \"DataFlair\"<\/pre>\n<p>Once we declare and initialize a variable, we can also reassign a value to it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var variableName: String = \"Swift\" \t\/\/declaring and initializing variable\r\nprint(variableName)\t\t\t\t\r\n\r\nvariableName = \"DataFlair\" \t\t\/\/reassigning a value to variable\r\nprint(variableName)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Swift<br \/>\nDataFlair<\/p>\n<h3>Naming Variables<\/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 variables\r\nvar DataFlair\r\nvar dataFlair\r\nvar _dataFlair\r\n\r\n\/\/Invalid variables\r\nvar 1dataFlair \r\nvar DataFlair#\r\nvar _DataFlair@\r\n<\/pre>\n<h3>Data Types &amp; Type Inference<\/h3>\n<p>Swift provides a rich set of data types that allow us to work with various kinds of data. Some of the data types used in Swift are:<\/p>\n<p><strong>Integers:<\/strong> Used to represent whole numbers.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var year: Int = 2023\r\n<\/pre>\n<p><strong>Float:<\/strong> Used to represent numbers with a fractional component. (~6 decimal digits)<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var temperature: Float = 25.8\r\n<\/pre>\n<p><strong>Double:<\/strong> Used to represent numbers with a fractional component. (~15 decimal digits)<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var pi: Float= 3.141592653589793\r\n<\/pre>\n<p><strong>String:<\/strong> stores a sequence of characters.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var example: String = \"DataFlair\"\r\n<\/pre>\n<p><strong>Character:<\/strong> represents individual textual elements.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var example: Character = \"D\"\r\n<\/pre>\n<p><strong>Booleans:<\/strong> stores true or false values.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var isWeekend: Bool = false\r\n<\/pre>\n<p><strong>Arrays:<\/strong> Used to store a collection of values of the same type.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var arrayExample: [String] = [\"DataFlair\", \"Swift\", \"Data Types\", \"Array\"]\r\n<\/pre>\n<p><strong>Dictionaries:<\/strong> Used to store key-value pairs.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var dictionaryExample: [String: Int] = [\"DataFlair\": 1, \"Swift\": 5]\r\n<\/pre>\n<p><strong>Tuples:<\/strong> Used to group multiple values of different types.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var tupleExample: (String, String) = (\"DataFlair\", \"Tuples\")\r\n<\/pre>\n<p><strong>Optional:<\/strong> Used to handle the absence of a value.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var phoneNumber: Int? = nil<\/pre>\n<p><strong>Custom Types:<\/strong> You can also create your own custom data types using struct, enum, or class.<\/p>\n<p>Swift has a type inference system that can deduce the data type of a variable based on its initial value. We can omit the type annotation during declaration, and Swift will infer the type for us.<\/p>\n<h3>Type Annotation<\/h3>\n<p>Type annotations allow us to specify the data type of a variable. 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\">var name: String\r\n<\/pre>\n<p>Type annotations play a crucial role in the type inference mechanism. When Swift can&#8217;t determine a type automatically, annotations guide the compiler, avoiding ambiguity and ensuring the correct type deduction.<\/p>\n<h3>Printing Variables<\/h3>\n<p>Printing variables are used to display information to users, logging or debugging. We can print variables using the &#8220;print&#8221; function or string interpolation.<\/p>\n<p><strong>For instance:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var name: String = \"DataFlair\"\r\nprint(name)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">DataFlair<\/p>\n<p>We can also embed variables 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\">var name: String = \"DataFlair\"\r\nprint( \"Name: \\(name)\")\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Name: DataFlair<\/p>\n<p>We use debugPrint to investigate objects, custom classes, or structs more thoroughly. It provides a detailed representation of the data and their relationships. We use debugPrint primarily for debugging purposes.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var name: String = \"DataFlair\"\r\ndebugPrint( \"Name: \\(name)\")\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&#8220;Name: DataFlair&#8221;<\/p>\n<p>In the above example, we could also use print to achieve the same result. However, debugPrint provides additional formatting and includes quotation marks around the printed string. This can be helpful to distinguish printed values from other outputs during debugging.<\/p>\n<h3>Variable Scope<\/h3>\n<p>In Swift, variables have a specific scope. The scope determines where the variable is accessible and where can use it. There are two types of variable scope in Swift: Global Scope and Local Scope.<\/p>\n<h4>Global Scope<\/h4>\n<p>Variables declared outside the context of any function or block have global scope. This means we can access it from any part of the code in the same file. We initialize the global variables once. It persists throughout the lifetime of the application.<\/p>\n<h4>Local Scope<\/h4>\n<p>Variables within a function or block have a local scope. This means we can access it within that particular function or block only. Local variables are instantiated in memory at runtime when the function or block is invoked. They are deallocated when the execution of the function or block is completed.<\/p>\n<p><strong>The following examples depict the usage of local and global scope:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var globalVariable = \"DataFlair\"\t\t\/\/declaration of global variable\r\n\r\nfunc scopeFunction() {\r\n \tvar localVariable = \"Scope\"\t\t\/\/declaration of local variable\r\n      print(localVariable)\t\t\t\r\n}\r\nprint(globalVariable)\t\t\t\t\/\/Output: DataFlair\r\nscopeFunction()\t\t\t\t\/\/Output: Scope\r\n\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">DataFlair Scope<\/p>\n<p><strong>Accessing a local variable out of its scope will lead to error.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func scopeFunction() {\r\n \tvar localVariable = \"Scope\"\t\t\/\/declaration of local variable\r\n      print(localVariable)\t\t\t\r\n}\r\nprint(localVariable)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Error: cannot find &#8216;localVariable&#8217; in scope<br \/>\nprint(localVariable) ^~~~~~~~~~~~~<\/p>\n<h3>Conclusion<\/h3>\n<p>Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications. This article depicts how to declare variables, how to initialize or assign values to them, how to name them, how to use different data types, how to leverage type inference, and how to manage variable scope. With this knowledge of variables, we can create powerful, data-driven Swift applications!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Variables store and manage data during program execution. They act as placeholders. A variable can hold different types of values, such as numbers, text, or collections. It allows us to manipulate data, perform calculations,&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":120500,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27789],"tags":[28282,28285,28592],"class_list":["post-117658","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift-tutorials","tag-swift-tutorial","tag-swift-variables","tag-variables-in-swift"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Swift Variables - DataFlair<\/title>\n<meta name=\"description\" content=\"Swift Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications.\" \/>\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-variables\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Variables - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Swift Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/swift-variables\/\" \/>\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-05T13:30:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-10-05T13:37:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.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=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift Variables - DataFlair","description":"Swift Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications.","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-variables\/","og_locale":"en_US","og_type":"article","og_title":"Swift Variables - DataFlair","og_description":"Swift Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications.","og_url":"https:\/\/data-flair.training\/blogs\/swift-variables\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-10-05T13:30:59+00:00","article_modified_time":"2023-10-05T13:37:02+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.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":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Swift Variables","datePublished":"2023-10-05T13:30:59+00:00","dateModified":"2023-10-05T13:37:02+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/"},"wordCount":806,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.webp","keywords":["swift tutorial","swift variables","variables in swift"],"articleSection":["Swift Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/swift-variables\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/","url":"https:\/\/data-flair.training\/blogs\/swift-variables\/","name":"Swift Variables - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.webp","datePublished":"2023-10-05T13:30:59+00:00","dateModified":"2023-10-05T13:37:02+00:00","description":"Swift Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/swift-variables\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-variables.webp","width":1200,"height":628,"caption":"swift variables"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/swift-variables\/#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 Variables"}]},{"@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\/117658","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=117658"}],"version-history":[{"count":4,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/117658\/revisions"}],"predecessor-version":[{"id":122744,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/117658\/revisions\/122744"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/120500"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=117658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=117658"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=117658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}