

{"id":120671,"date":"2024-01-04T18:00:58","date_gmt":"2024-01-04T12:30:58","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=120671"},"modified":"2024-01-04T18:47:39","modified_gmt":"2024-01-04T13:17:39","slug":"swift-classes-and-objects","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/","title":{"rendered":"Swift Classes and Objects with Examples"},"content":{"rendered":"<p>Classes signify being a part of Object Oriented Programming. It is a blueprint for the creation of objects. It helps in defining the behavior and structure of an object. In this article, we\u2019ll discuss how to define a class and its objects and how to initialize it. We\u2019ll go through related concepts along with relevant examples.<\/p>\n<h2>Defining a Swift Class<\/h2>\n<p>We define a swift class by writing the class keyword followed by the class name. <strong>The syntax for defining a class is as follows.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class ClassName{\r\n    \/\/class statements\r\n}<\/pre>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Company{\r\n    var companyName = \"\"\r\n}<\/pre>\n<h3>Swift Class Objects<\/h3>\n<p>Objects help us create instances of the classes. We can use these objects to use in our code as per our requirements.<\/p>\n<p><strong>Syntax to create an object.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var newObjectName = ClassName()<\/pre>\n<p><strong>In the example given below, we create an instance company1 of the class Company.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Company{\r\n    var companyName = \"DataFlair\"\r\n    var foundingYear = 2014\r\n}\r\n\r\nvar company1 = Company()<\/pre>\n<p>A single class can have multiple objects. We can create multiple instances of these classes based on our requirements.<\/p>\n<h3>Class Properties and Methods in Swift<\/h3>\n<p>Every class can have its own properties and methods. We declare variables\/constants related to the class as Properties. We define functions belonging to a particular class as Class methods.<\/p>\n<p>We can access these methods and properties using the dot notation \u2018.\u2019.<\/p>\n<p><strong>The following example depicts how we can define the properties and methods of a class. It also shows how we can access these.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Company{\r\n    var companyName = \"DataFlair\"\r\n    var foundingYear = 2014\r\n    \r\n    func greet(){\r\n        print(\"Hello from \\(companyName)\")\r\n    }\r\n}\r\n\r\nvar company1 = Company()\r\ncompany1.greet()\r\nprint(company1.foundingYear)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello from DataFlair<br \/>\n2014<\/p>\n<h3>Swift Class Initializer<\/h3>\n<p>In the examples above, we have given initial values to all our class properties. These values are known as the default values of these properties. We can also initialize these values. We do that with the help of an initializer.<\/p>\n<p><strong>The syntax of creating an initializer is as follows.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class ClassName{\r\nvar property1: dataType\r\nvar property2: dataType\r\n\r\ninit(property1, property2){\r\n    \/\/assignment statements\r\n}\r\n}<\/pre>\n<p>Since we are using an initializer in the class, we need to pass these property values when we create an instance of the class. <strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Company{\r\n    var companyName: String\r\n    var foundingYear: Int\r\n    \r\n    init(companyName: String, foundingYear: Int){\r\n        self.companyName = companyName\r\n        self.foundingYear = foundingYear\r\n    }\r\n}\r\n\r\nvar company1 = Company(companyName: \"DataFlair\", foundingYear: 2014)\r\nprint(company1.companyName, company1.foundingYear)\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>DataFlair 2014<\/p>\n<h3>Class as Reference Type<\/h3>\n<p>Classes are reference types in Swift. This means that when we assign an instance of a class to a variable\/constant or we pass it as an argument in a function, we work with its reference to the same object stored in the memory. If we change one of the references, then it affects all the references to that object in the program.<\/p>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class ReferenceTypeExample {\r\n    var name: String\r\n    init(name: String) {\r\n        self.name = name\r\n    }\r\n}\r\n\r\nlet example1 = ReferenceTypeExample(name: \"Swift\")\r\n\/\/ example2 references the same object\r\nlet example2 = example1 \r\nprint(\"Original values: \\(example1.name), \\(example2.name)\")\r\n\r\nexample2.name = \"DataFlair\"\r\n\/\/ both example1 &amp; example2 points to the same object\r\nprint(\"Updated values: \\(example1.name), \\(example2.name)\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Original values:<\/strong> Swift, Swift<br \/>\n<strong>Updated values:<\/strong> DataFlair, DataFlair<\/p>\n<h3>Class Identity Operators in Swift<\/h3>\n<p>In Swift, we can create several class instances. Some of these multiple instances might point to the same reference. We can use identity operators to verify these variables or constants pointing to specific instances.<\/p>\n<p><strong>The table below explains how to check for identical and non-identical identifiers.<\/strong><\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Identical<\/b><\/td>\n<td><b>Not Identical<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">=== Operator<\/span><\/td>\n<td><span style=\"font-weight: 400\">!== Operator<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">A statement is true if the given identifiers are pointing to the same instance.<\/span><\/td>\n<td><span style=\"font-weight: 400\">A statement is false if the given identifiers are pointing to the same instance.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Class and Structure in Swift<\/h3>\n<p>Classes and Structures are pretty similar in some contexts. However they have some significant differences between them, which makes them useful for separate use cases. <strong>We have discussed the differences between a class and structure below.<\/strong><\/p>\n<h4>Differences of Class &amp; Structure<\/h4>\n<table>\n<tbody>\n<tr>\n<td><b>Classes<\/b><\/td>\n<td><b>Structures<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Class is a reference type.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Structure is a value type.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">They support inheritance.<\/span><\/td>\n<td><span style=\"font-weight: 400\">They do not support inheritance.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Properties are mutable even when declared as a constant.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Properties are immutable if declared as a constant.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">They have a separate initialiser to initialize the properties<\/span><\/td>\n<td><span style=\"font-weight: 400\">They have a memberwise initialiser to initialize the properties by default<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Conclusion<\/h3>\n<p>Classes are a blueprint of object-oriented programming. In this article, we have discussed the basics of a class. We have seen how to define a swift class and how to use and access its properties and methods. We have also seen how to use an initializer and identity operators in swift. We also understood the differences between a class and a structure.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Classes signify being a part of Object Oriented Programming. It is a blueprint for the creation of objects. It helps in defining the behavior and structure of an object. In this article, we\u2019ll discuss&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":120673,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27789],"tags":[28795,21771,28793,28794,28287],"class_list":["post-120671","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift-tutorials","tag-class-in-swift","tag-swift","tag-swift-class","tag-swift-classes","tag-swift-tutorials"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Swift Classes and Objects with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"In this article, We have seen how to define a swift class and how to use and access its properties and methods.\" \/>\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-classes-and-objects\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Classes and Objects with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"In this article, We have seen how to define a swift class and how to use and access its properties and methods.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/\" \/>\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=\"2024-01-04T12:30:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-01-04T13:17:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.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 Classes and Objects with Examples - DataFlair","description":"In this article, We have seen how to define a swift class and how to use and access its properties and methods.","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-classes-and-objects\/","og_locale":"en_US","og_type":"article","og_title":"Swift Classes and Objects with Examples - DataFlair","og_description":"In this article, We have seen how to define a swift class and how to use and access its properties and methods.","og_url":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-01-04T12:30:58+00:00","article_modified_time":"2024-01-04T13:17:39+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.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-classes-and-objects\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Swift Classes and Objects with Examples","datePublished":"2024-01-04T12:30:58+00:00","dateModified":"2024-01-04T13:17:39+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/"},"wordCount":639,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.webp","keywords":["class in swift","Swift","swift class","swift classes","swift tutorials"],"articleSection":["Swift Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/","url":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/","name":"Swift Classes and Objects with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.webp","datePublished":"2024-01-04T12:30:58+00:00","dateModified":"2024-01-04T13:17:39+00:00","description":"In this article, We have seen how to define a swift class and how to use and access its properties and methods.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/09\/swift-classes.webp","width":1200,"height":628,"caption":"swift classes"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/swift-classes-and-objects\/#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 Classes and Objects with Examples"}]},{"@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\/120671","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=120671"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120671\/revisions"}],"predecessor-version":[{"id":132906,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/120671\/revisions\/132906"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/120673"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=120671"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=120671"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=120671"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}