{"id":76,"date":"2020-11-25T14:18:58","date_gmt":"2020-11-25T14:18:58","guid":{"rendered":"http:\/\/mohammadreza.me\/blog\/?p=76"},"modified":"2022-11-29T12:10:58","modified_gmt":"2022-11-29T12:10:58","slug":"swift-extensions","status":"publish","type":"post","link":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/","title":{"rendered":"Swift Extensions"},"content":{"rendered":"\n<p>Extensions in <a href=\"http:\/\/mohammadreza.me\/blog\/category\/swift\/\">Swift<\/a> are very useful and super powerful which can help us organize our codes better, and increase maintainability and readability of your codes.<br>A very interesting point of Extensions is that you can write extensions for class, struct, protocol, or enum even you don\u2019t have access to them.<\/p>\n\n\n\n<p>In this tutorial, I explain some functionality of extension in Swift, but let\u2019s take a look at the definition of extension in Swift documentation:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Extensions<\/strong> add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as <em>retroactive modeling<\/em>).<\/p>\n<\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<p>Extensions in Swift can:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Add computed instance properties and computed type properties<\/li>\n\n\n\n<li>Define instance methods and type methods<\/li>\n\n\n\n<li>Provide new initializers<\/li>\n\n\n\n<li>Define subscripts<\/li>\n\n\n\n<li>Define and use new nested types<\/li>\n\n\n\n<li>Make an existing type conform to a protocol<\/li>\n<\/ul>\n\n\n\n<div style=\"height:32px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Extension Syntax<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">extension SomeType {\n\t\/\/ new functionality to add to SomeType goes here\n}<\/pre>\n\n\n\n<div style=\"height:20px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n\n\n\n<div style=\"height:20px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p>Ok, let\u2019s write some examples:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">extension Array where Element == String {\n    func alphabeticallySort() -> Array {\n        return self.sorted { $0.lowercased() &lt; $1.lowercased() }\n    }\n}<\/pre>\n\n\n\n<p>With this extension, we add alphabeticallySort() method to the Array class to sort arrays alphabetically.<\/p>\n\n\n\n<div style=\"height:32px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">extension Int {\n    func percentOf(_ value: Int) -> Double {\n        guard value >= 0 else {\n            print(\"wrong percentage number...\")\n            return -1\n        }\n        return (Double(self * value) \/ 100)\n    }\n}\n\n3.percentOf(10) \/\/ output = 0.3<\/pre>\n\n\n\n<p>With this extension, we add percentOf(_ value: Int) method to the Int class to calculate the percent of the number with the value percentage. As you can see, percentOf is a Swift function and we can add parameters to it.<\/p>\n\n\n\n<div style=\"height:32px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Computed properties<\/h2>\n\n\n\n<p>Swift doesn\u2019t let us add stored properties in extensions, so we must use computed properties instead.<\/p>\n\n\n\n<p>In this example, I add isOdd property to Int class that returns true if the number is odd:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">extension Int {\n    var isOdd : Bool {\n        return self % 2 != 0\n    }\n}\n\n3.isOdd \/\/ output = true<\/pre>\n\n\n\n<div style=\"height:32px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Increase controllers readability:<\/h2>\n\n\n\n<p>The most useful application of extensions in Swift which I use in my projects is the ability to separate codes of controllers.<br>We all met massive controllers in our projects, especially in big projects.<\/p>\n\n\n\n<p>One way that we can increase the readability of controller\u2019s codes is using extensions.<\/p>\n\n\n\n<p>For example, we can separate protocols of UITableView from the base class, like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class DetaiViewController: UIViewController {\n    \n}\n\/\/ TableView DataSource\nextension DetaiViewController: UITableViewDataSource {\n    \n    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n        \n    }\n    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n        \n    }\n}<\/pre>\n\n\n\n<p>Or we can separate relative methods which we use in controllers:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ MARK: - Setup View\nextension DetaiViewController {\n    private func setupUI() {\n        \n    }\n}\n \/\/ MARK: - Calculate Score\nextension DetaiViewController {\n    private func calculateScore() {\n        \n    }\n    private func convertScoresToGift() {\n        \n    }\n}<\/pre>\n\n\n\n<p>You can read more about extensions in <a href=\"https:\/\/docs.swift.org\/swift-book\/LanguageGuide\/Extensions.html\">Swift Documentation<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Extensions in Swift are very useful and super powerful which can help us organize our codes better, and increase maintainability and readability of your codes.A very interesting point of Extensions is that you can write extensions for class, struct, protocol, or enum even you don\u2019t have access to them. In this tutorial, I explain some &hellip; <a href=\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Swift Extensions<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":43,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-76","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swift Extensions - Swift with Reza<\/title>\n<meta name=\"description\" content=\"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Extensions - Swift with Reza\" \/>\n<meta property=\"og:description\" content=\"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\" \/>\n<meta property=\"og:site_name\" content=\"Swift with Reza\" \/>\n<meta property=\"article:published_time\" content=\"2020-11-25T14:18:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-29T12:10:58+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1621\" \/>\n\t<meta property=\"og:image:height\" content=\"912\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Reza\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Reza\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\",\"url\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\",\"name\":\"Swift Extensions - Swift with Reza\",\"isPartOf\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png\",\"datePublished\":\"2020-11-25T14:18:58+00:00\",\"dateModified\":\"2022-11-29T12:10:58+00:00\",\"author\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c\"},\"description\":\"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...\",\"breadcrumb\":{\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage\",\"url\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png\",\"contentUrl\":\"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png\",\"width\":1621,\"height\":912,\"caption\":\"swift extension\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/mohammadreza.me\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Swift Extensions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#website\",\"url\":\"https:\/\/mohammadreza.me\/blog\/\",\"name\":\"Swift with Reza\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/mohammadreza.me\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c\",\"name\":\"Reza\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g\",\"caption\":\"Reza\"},\"sameAs\":[\"http:\/\/mohammadreza.me\/blog\"],\"url\":\"https:\/\/mohammadreza.me\/blog\/author\/mohammadreza\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift Extensions - Swift with Reza","description":"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...","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:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/","og_locale":"en_US","og_type":"article","og_title":"Swift Extensions - Swift with Reza","og_description":"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...","og_url":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/","og_site_name":"Swift with Reza","article_published_time":"2020-11-25T14:18:58+00:00","article_modified_time":"2022-11-29T12:10:58+00:00","og_image":[{"width":1621,"height":912,"url":"http:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png","type":"image\/png"}],"author":"Reza","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Reza","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/","url":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/","name":"Swift Extensions - Swift with Reza","isPartOf":{"@id":"https:\/\/mohammadreza.me\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage"},"image":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage"},"thumbnailUrl":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png","datePublished":"2020-11-25T14:18:58+00:00","dateModified":"2022-11-29T12:10:58+00:00","author":{"@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c"},"description":"Extensions in Swift are very useful and super powerful which can help us organize your codes better, and increase maintainability...","breadcrumb":{"@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#primaryimage","url":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png","contentUrl":"https:\/\/mohammadreza.me\/blog\/wp-content\/uploads\/2020\/11\/swift-extension-1.png","width":1621,"height":912,"caption":"swift extension"},{"@type":"BreadcrumbList","@id":"https:\/\/mohammadreza.me\/blog\/2020\/11\/25\/swift-extensions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/mohammadreza.me\/blog\/"},{"@type":"ListItem","position":2,"name":"Swift Extensions"}]},{"@type":"WebSite","@id":"https:\/\/mohammadreza.me\/blog\/#website","url":"https:\/\/mohammadreza.me\/blog\/","name":"Swift with Reza","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/mohammadreza.me\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/9ab155944216224664701a81bc56cf8c","name":"Reza","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/mohammadreza.me\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/1a4d35be7e8c853112a49822b1ccc907e5855a115f93d587800a7d71f2255f01?s=96&d=mm&r=g","caption":"Reza"},"sameAs":["http:\/\/mohammadreza.me\/blog"],"url":"https:\/\/mohammadreza.me\/blog\/author\/mohammadreza\/"}]}},"wps_subtitle":"Extensions in Swift are very useful and super powerful which can help us organize our codes better, and increase maintainability and readability of our codes.","_links":{"self":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts\/76","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/comments?post=76"}],"version-history":[{"count":6,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts\/76\/revisions"}],"predecessor-version":[{"id":171,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/posts\/76\/revisions\/171"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/media\/43"}],"wp:attachment":[{"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/media?parent=76"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/categories?post=76"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohammadreza.me\/blog\/wp-json\/wp\/v2\/tags?post=76"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}