{"id":1014,"date":"2015-11-09T23:00:46","date_gmt":"2015-11-09T23:00:46","guid":{"rendered":"http:\/\/www.yeahbutisitswift.com\/?p=1014"},"modified":"2015-11-11T09:16:19","modified_gmt":"2015-11-11T09:16:19","slug":"quick-start-guide-to-swift-part-4","status":"publish","type":"post","link":"http:\/\/www.yeahbutisitswift.com\/?p=1014","title":{"rendered":"Quick Start Guide to Swift: Part 4"},"content":{"rendered":"<p>Welcome to the fourth tutorial in the series. Today we\u2019ll cover many of Swift\u2019s object-oriented features.<\/p>\n<h3>What you will learn&#8230;<\/h3>\n<ul>\n<li>Basic object-oriented concepts with Swift<\/li>\n<\/ul>\n<h3>What you should know&#8230;<\/h3>\n<ul>\n<li>A familiarity with object-oriented programming concepts<\/li>\n<li>The basics of the Swift programming language from <a href=\"?p=522\" target=\"_blank\">part one<\/a>, <a href=\"?p=324\" target=\"_blank\">two<\/a> and <a href=\"?p=999\" target=\"_blank\">three<\/a><\/li>\n<\/ul>\n<p>Swift doesn\u2019t favour one programming paradigm over another. However it does provide excellent object-oriented features, which we\u2019ll explore the basics of.<\/p>\n<p>Many of the topics covered previously, including functions and structures, will be directly applicable to our coverage of Swift\u2019s object-oriented features. Today\u2019s tutorial will walk you through the steps to build and use a class that models a popular weapon from the Star Wars universe.<\/p>\n<p>If you\u2019re comfortable with the topics covered in <a href=\"?p=999\" target=\"_blank\">part three<\/a> then getting to grips with the basics of object-oriented programming in Swift shouldn\u2019t be too much of a stretch.<\/p>\n<p><!--more--><\/p>\n<h1>Getting Started<\/h1>\n<p>By now you should feel comfortable with the content covered in the first three tutorials. If not then please revisit them:<\/p>\n<ul>\n<li><a href=\"?p=522\" target=\"_blank\">Quick Start Guild To Swift: Part 1<\/a><\/li>\n<li><a href=\"?p=324\" target=\"_blank\">Quick Start Guild To Swift: Part 2<\/a><\/li>\n<li><a href=\"?p=999\" target=\"_blank\">Quick Start Guild To Swift: Part 3<\/a><\/li>\n<\/ul>\n<p>To try out this tutorial&#8217;s code examples, install Xcode and create a playground.<br \/>\nDetail regarding that can be found in the <a href=\"?p=522\" target=\"_blank\">first tutorial<\/a>.<\/p>\n<h2>Classes<\/h2>\n<p>A class is declared using the <code>class<\/code> keyword and its definition is placed within a pair of braces. Its general form looks like this:<\/p>\n<p><codeswift>class ClassName {<br \/>\n&nbsp;&nbsp;\/\/ Implementation goes here<br \/>\n}<\/codeswift><\/p>\n<p>Unlike languages such as Objective-C and C++, Swift does not require you to write a separate interface and implementation file when creating a class. Instead everything is kept within a single file.<\/p>\n<div class=\"zilla-alert white\"> For the avoidance of doubt, every time you define a new class or structure, you are effectively defining a brand new type in Swift.<\/p>\n<p>For this reason it is encouraged that all classes and structures use <a href=\"http:\/\/en.wikipedia.org\/wiki\/CamelCase\" target=\"_blank\">UpperCamelCase<\/a> names (such as <codeswift>ScorePanel<\/codeswift> and <codeswift>DataManager<\/codeswift>) to match the capitalisation of Swift&#8217;s standard types. Conversely, any properties and methods you define should use <a href=\"http:\/\/en.wikipedia.org\/wiki\/CamelCase\" target=\"_blank\">lowerCamelCase<\/a> names (such as <codeswift>ammunitionCount<\/codeswift> and <codeswift>engageHyperdrive<\/codeswift>) to differentiate them from type names. <\/div>\n<p>Functionality is added to a class by defining properties and methods for it. Let&#8217;s begin by defining a class that represents an <a href=\"http:\/\/starwars.wikia.com\/wiki\/Ion_cannon\" target=\"_blank\">ion cannon<\/a>:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = 20<br \/>\n}<\/codeswift><\/p>\n<p>Our class defines two stored properties: <codeswift>capacity<\/codeswift> and <codeswift>ammunition<\/codeswift>. They represent the cannon&#8217;s ammunition capacity and its current ammunition count respectively. Since the capacity can&#8217;t be changed it has been defined as a constant.<\/p>\n<h3>Instantiating a Class<\/h3>\n<p>A class instance can be created with initializer syntax:<\/p>\n<p><codeswift>let cannon = IonCannon()<\/codeswift><\/p>\n<p>If you think back to the section on structures in <a href=\"?p=999\" target=\"_blank\">part three<\/a>, you may reasonably assume that a <strong><em>memberwise initializer<\/em><\/strong> is provided for each class you define. For example, you may try to create an instance of your ion cannon with the following:<\/p>\n<p><codeswift>let cannon = IonCannon(ammunition: 15)<\/codeswift><\/p>\n<p>However, unlike structures, class instances do not receive a default memberwise initializer. The line of code above would result in a compile-time error.<\/p>\n<h3>Classes are Reference Types<\/h3>\n<p>Until now, every type we\u2019ve looked at, including structures, has been a value type. Classes however are reference types.<\/p>\n<p>Remember, a value type is copied when it is assigned to a variable or constant, or when being passed to a function. With classes, a reference to the same instance is used instead.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<p><codeswift>let cannon1 = IonCannon()<br \/>\nlet cannon2 = cannon1<\/codeswift><\/p>\n<p>The code above creates two constants that point to the exact same <codeswift>IonCannon<\/codeswift> instance. We can prove this by modifying the value of one&#8217;s stored property and seeing the change reflected in the other:<\/p>\n<p><codeswift>cannon1.ammunition = 10<br \/>\nprint(&#8220;cannon1.ammunition: \\(cannon1.ammunition)&#8221;)<br \/>\nprint(&#8220;cannon2.ammunition: \\(cannon2.ammunition)&#8221;)<\/codeswift><\/p>\n<p>The following will be output:<\/p>\n<p><codeswift>cannon1.ammunition: 10<br \/>\ncannon2.ammunition: 10<\/codeswift><\/p>\n<p>While structures and classes are very similar, this is one major difference between the two and should be a consideration when deciding whether it&#8217;s best to define a structure or class for a particular type you are modelling.<\/p>\n<div class=\"zilla-alert white\"> If you&#8217;re familiar with languages such as C++ or Objective-C then you&#8217;ll be used to creating pointers to refer to your class instances. A Swift constant or variable that refers to an instance of a class is similar to a pointer in these languages but does not require you to write an asterisk (<codeswift>*<\/codeswift>) to indicate that you&#8217;re creating a class reference. Instead, in Swift, these references are defined like any other constant or variable. Languages such as ActionScript 3 and Java work in a similar fashion to Swift in this regard. <\/div>\n<h3>Classes As Constants<\/h3>\n<p>We saw in <a href=\"?p=999\" target=\"_blank\">part three<\/a> that declaring a constant instance of a structure will prevent you from modifying any variable properties belonging to that instance.<\/p>\n<p>The same isn&#8217;t true of class instances, which are reference types. If you assign an instance of a reference type to a constant, you can still change any variable properties that belong to it. You can&#8217;t however, assign your constant to another class instance after it has been set. Let&#8217;s look at a few quick examples:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.ammunition = 10<\/codeswift><\/p>\n<p>The code snippet above is perfectly valid. Even though we use a constant to refer to our <codeswift>IonCannon<\/codeswift> instance, we are still able to modify properties belonging to it.<\/p>\n<p>However, we can&#8217;t set our <codeswift>cannon<\/codeswift> constant to any other <codeswift>IonCannon<\/codeswift> instances:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.ammunition = 10<br \/>\n<codeswiftbold>cannon = IonCannon()<\/codeswiftbold><\/codeswift><\/p>\n<p>The line above will result in the following compile-time error: <code>Cannot assign to value: 'cannon' is a 'let' constant<\/code>.<\/p>\n<h3>Identity Operators<\/h3>\n<p>When working with reference types such as class instances, it&#8217;s possible for multiple constants and variables to refer to the exact same instance of a class. Here&#8217;s an example:<\/p>\n<p><codeswift><codeswiftbold>let cannon1 = IonCannon()<\/codeswiftbold><br \/>\nlet cannon2 = IonCannon()<br \/>\n<codeswiftbold>let cannon3 = cannon1<\/codeswiftbold><\/codeswift><\/p>\n<p>In the code above, the constants <codeswift>cannon1<\/codeswift> and <codeswift>cannon3<\/codeswift> refer to the exact same instance of the <codeswift>IonCannon<\/codeswift> class. The <codeswift>cannon2<\/codeswift> constant however refers to a different instance of <codeswift>IonCannon<\/codeswift>. <\/p>\n<p>On occasions, you may want to know if two constants or variables refer to the exact same class instance. Swift provides the &quot;identical to&quot; operator (<code>===<\/code>) for this purpose. Try entering the following into your playground:<\/p>\n<p><codeswift>let cannon1 = IonCannon()<br \/>\nlet cannon2 = IonCannon()<br \/>\nlet cannon3 = cannon1<\/codeswift><\/p>\n<p><codeswift>var sameInstance = cannon1 === cannon2<br \/>\nprintln(&#8220;cannon1 and cannon2 refer to the same instance: \\(sameInstance)&#8221;)<\/codeswift><\/p>\n<p><codeswift>sameInstance = cannon1 === cannon3<br \/>\nprintln(&#8220;cannon1 and cannon3 refer to the same instance: \\(sameInstance)&#8221;)<\/codeswift><\/p>\n<p><codeswift>sameInstance = cannon2 === cannon3<br \/>\nprintln(&#8220;cannon2 and cannon3 refer to the same instance: \\(sameInstance)&#8221;)<\/codeswift><\/p>\n<p>It will result in the following being output:<\/p>\n<p><codeswift>cannon1 and cannon2 refer to the same instance: false<br \/>\ncannon1 and cannon3 refer to the same instance: true<br \/>\ncannon2 and cannon3 refer to the same instance: false<\/codeswift><\/p>\n<p>As you might expect, Swift also provides the &quot;not identical to&quot; operator (<code>!==<\/code>) to check if two constants or variables are referring to different instances.<\/p>\n<h3>Properties<\/h3>\n<p>We spent considerable time discussing properties when covering structures in <a href=\"?p=999\" target=\"_blank\">part three<\/a>. The good news is that everything that applies to properties for structures also applies to classes.<\/p>\n<p>We\u2019ll spend just a few moments on the subject to help build out our example <codeswift>IonCannon<\/codeswift> class and also to highlight a few things of note.<\/p>\n<h4>Type Properties<\/h4>\n<p>Remember, type properties are useful for defining values that are universal to all instances of a particular type. Type properties are defined using the <code>static<\/code> keyword.<\/p>\n<p>While we&#8217;re on the subject, let&#8217;s change our class&#8217; <codeswift>capacity<\/codeswift> stored property to a type property:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;<codeswiftbold>static<\/codeswiftbold> let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = 20<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> It&#8217;s worth noting that for <strong><em>computed type properties<\/em><\/strong> of a class, you can use the <code>class<\/code> keyword instead of <code>static<\/code>. Doing so will allow a subclass to override the superclass&#8217; implementation. We\u2019ll cover this at a later date in part five. <\/div>\n<p>We can also explicitly set our variable property, <codeswift>ammunition<\/codeswift>, to the value of our static constant property, <codeswift>capacity<\/codeswift>. Make the following change to your class:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = <codeswiftbold>IonCannon.capacity<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>This will make our code more maintainable.<\/p>\n<h4>Property Observers<\/h4>\n<p>To ensure our ion cannon example is as robust as possible, it\u2019s important that the <codeswift>ammunition<\/codeswift> property is never a negative value or has a value greater than the cannon\u2019s capacity.<\/p>\n<p>For completeness, add a property observer that constrains the value of the <codeswift>ammunition<\/codeswift> property:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;<codeswiftbold>didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Verify that everything is working as expected by attempting to set invalid values for the <codeswift>ammunition<\/codeswift> property:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.ammunition = -1<br \/>\nprint(&#8220;cannon.ammunition: \\(cannon.ammunition)&#8221;)<br \/>\ncannon.ammunition = 21<br \/>\nprint(&#8220;cannon.ammunition: \\(cannon.ammunition)&#8221;)<br \/>\ncannon.ammunition = 10<br \/>\nprint(&#8220;cannon.ammunition: \\(cannon.ammunition)&#8221;)<\/codeswift><\/p>\n<p>The following will be output:<\/p>\n<p><codeswift>cannon.ammunition: 0<br \/>\ncannon.ammunition: 20<br \/>\ncannon.ammunition: 10<\/codeswift><\/p>\n<p>As you can see from the results above, the value of the instance\u2019s <codeswift>ammunition<\/codeswift> property is always set to an integer value between <codeswift>0<\/codeswift> and <codeswift>20<\/codeswift> inclusive.<\/p>\n<h3>Methods<\/h3>\n<p>Methods have the exact same syntax as functions, which we covered in <a href=\"?p=999\" target=\"_blank\">part three<\/a>. A method belongs to a particular class and provides a means to access and modify an instance of that class in some way.<\/p>\n<p>Let\u2019s add a simple method to our class that is used to reload the cannon\u2019s ammunition:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;<codeswiftbold>func reload() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>We can now easily reset our cannon to full capacity by calling the <codeswift>reload<\/codeswift> method. Here\u2019s an example:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.ammunition = 10<br \/>\nprint(&#8220;cannon.ammunition: \\(cannon.ammunition)&#8221;)<br \/>\ncannon.reload()<br \/>\nprint(&#8220;cannon.ammunition: \\(cannon.ammunition)&#8221;)<\/codeswift><\/p>\n<p>You should see the following output in the sidebar:<\/p>\n<p><codeswift>cannon.ammunition: 10<br \/>\ncannon.ammunition: 20<\/codeswift><\/p>\n<p>In other words, calling <codeswift>reload<\/codeswift> has set the cannon\u2019s capacity from <codeswift>10<\/codeswift> back to <codeswift>20<\/codeswift>.<\/p>\n<h4>Parameters<\/h4>\n<p>As with functions, you can optionally define one or more typed parameters for class methods.<\/p>\n<p>Let\u2019s add a method to our <codeswift>IonCannon<\/codeswift> class that fires a burst of ion pulses. The method takes a single parameter that is used to specify the number of ion pulses to fire:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func reload() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;<codeswiftbold>func fireBurstOf(amount: Int) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition -= amount<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>We&#8217;ve just added a method named <codeswift>fireBurstOf(_:)<\/codeswift> that simulates our ion cannon firing a specified number of pulses. Calling this method will deplete the instance&#8217;s <codeswift>ammunition<\/codeswift> property.<\/p>\n<p>Let&#8217;s use our method to fire 4 ion bursts at the incoming Imperial fleet:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.fireBurstOf(4)<\/codeswift><\/p>\n<p>We can verify that the pulses were fired by querying our instance&#8217;s <codeswift>ammunition<\/codeswift> property:<\/p>\n<p><codeswift>print(&#8220;The cannon has enough charge remaining to fire \\(cannon.ammunition) more ion bursts.&#8221;)<\/codeswift><\/p>\n<p>The line above will result in the following being sent to the appropriate output:<\/p>\n<p><code>The cannon has enough charge remaining to fire 16 more ion bursts.<\/code><\/p>\n<p>Call the method again to fire 2 more bursts:<\/p>\n<p><codeswift>cannon.fireBurstOf(2)<\/codeswift><\/p>\n<p>Your ion cannon&#8217;s <codeswift>ammunition<\/codeswift> property will now have a value of <codeswift>14<\/codeswift>. Hopefully you took out a few Star Destroyers with those shots.<\/p>\n<p>It&#8217;s possible to provide multiple versions of a method. Here&#8217;s an alternative version of our <codeswift>fireBurstOf(_:)<\/codeswift> method that expects two parameters &#8211; <codeswift>amount<\/codeswift> and <codeswift>numberOfTimes<\/codeswift>:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func reload() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func fireBurstOf(amount: Int) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition -= amount<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;<codeswiftbold>func fireBurstOf(amount: Int, numberOfTimes: Int) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition -= (amount * numberOfTimes)<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>The <codeswift>numberOfTimes<\/codeswift> parameter is used to specify multiple repetitions of our burst of ion pulses. For example, here&#8217;s how to fire off a burst of three ion pulses, four times:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.fireBurstOf(3, numberOfTimes: 4)<\/codeswift><\/p>\n<p>Notice that we explicitly stated the name of the method&#8217;s second parameter when making our call. This should seem odd to you as we didn&#8217;t explicitly define an external name for our second parameter. In Swift, the default behaviour of local and external parameter names in methods differs from functions. Swift gives the first parameter in a method a local parameter name by default, but gives subsequent parameter names both a local and external parameter name.<\/p>\n<p>The reason for this is that Swift attempts to make method naming and calling similar to that of Objective-C. In Objective-C, the name of a method typically refers to the method&#8217;s first parameter using a preposition such as <strong>with<\/strong>, <strong>for<\/strong>, <strong>by<\/strong>, <strong>of<\/strong> etc. We can see this in our <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method. The use of the <strong>Of<\/strong> preposition helps the method to be read as a sentence when it is called.<\/p>\n<div class=\"zilla-alert white\"> This naming and calling convention will be familiar to anyone who has coded in Objective-C. Those from other programming languages will likely take time to warm to it. It&#8217;s actually a very expressive feature of both Swift and Objective-C and when used properly can result in code that&#8217;s extremely easy to read. <\/div>\n<h4>Return Values<\/h4>\n<p>As you would expect, values can be returned from methods in exactly the same manner as functions.<\/p>\n<p>As a quick example, let\u2019s modify our <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method so that it returns the number of ion pulses that were actually fired. This will be useful since the requested number of pulses to fire may actually be greater than the cannon\u2019s current ammunition level.<\/p>\n<p>Change your method\u2019s definition to this: <\/p>\n<p><codeswift>func fireBurstOf(amount: Int, numberOfTimes: Int) <codeswiftbold>-&gt; Int<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;<codeswiftbold>var remainingShots = amount * numberOfTimes<br \/>\n&nbsp;&nbsp;var actuallyFired = 0<br \/>\n&nbsp;&nbsp;while ammunition &gt; 0 &#038;&#038; remainingShots &gt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition&#45;&#45;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;remainingShots&#45;&#45;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;actuallyFired++<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;return actuallyFired<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>Cool! We can now tell exactly how many ion pulses were fired on each attempt. Here\u2019s a quick example of how to use our updated method:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\nprint(&#8220;Available ion pulses: \\(cannon.ammunition)&#8221;)<br \/>\nvar pulsesFired = cannon.fireBurstOf(17, numberOfTimes: 1)<br \/>\nprint(&#8220;Attempting to fire 17 ion pulses: \\(pulsesFired) actually fired with \\(cannon.ammunition) remaining.&#8221;)<br \/>\npulsesFired = cannon.fireBurstOf(5, numberOfTimes: 1)<br \/>\nprint(&#8220;Attempting to fire 5 ion pulses. \\(pulsesFired) actually fired with \\(cannon.ammunition) remaining.&#8221;)<\/codeswift><\/p>\n<p>The following will be output to the sidebar:<\/p>\n<p><codeswift>Available ion pulses: 20<br \/>\nAttempting to fire 17 ion pulses: 17 actually fired with 3 remaining.<br \/>\nAttempting to fire 5 ion pulses: 3 actually fired with 0 remaining.<\/codeswift><\/p>\n<p>As you can see from the final line above. We attempted to fire 5 ion pulses when there was only enough ammunition for 3. Therefore our <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method returned a value of <codeswift>3<\/codeswift> indicating that only three ion pulses were actually fired. <\/p>\n<h4>Default Parameter Values<\/h4>\n<p>As with functions, a default value can be assigned to parameters of a method. We can default our <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method&#8217;s <codeswift>numberOfTimes<\/codeswift> parameter to <codeswift>1<\/codeswift>. Doing so will allow us to remove our class\u2019 original <codeswift>fireBurstOf(_:)<\/codeswift> method while still providing the same API. Make the following changes:<\/p>\n<p><codeswift><strike style=\"color:#990000\">func fireBurstOf(amount: Int) {<\/strike><br \/>\n&nbsp;&nbsp;<strike style=\"color:#990000\">ammunition -= amount<\/strike><br \/>\n<strike style=\"color:#990000\">}<\/strike><br \/>\n&nbsp;<br \/>\nfunc fireBurstOf(amount: Int, numberOfTimes: Int <codeswiftbold>= 1<\/codeswiftbold>) -&gt; Int {<br \/>\n&nbsp;&nbsp;var remainingShots = amount * numberOfTimes<br \/>\n&nbsp;&nbsp;var actuallyFired = 0<br \/>\n&nbsp;&nbsp;while ammunition &gt; 0 &#038;&#038; remainingShots &gt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;remainingShots&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;actuallyFired++<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;return actuallyFired<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> Notice that we added a default value of <codeswift>1<\/codeswift> to the <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method\u2019s definition above. It\u2019s an easy code change to miss. <\/div>\n<p>Thanks to our default parameter, we can still make the following two types of calls even though we\u2019ve removed one of our methods:<\/p>\n<ul>\n<li><codeswift>fireBurstOf(_:)<\/codeswift><\/li>\n<li><codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift><\/li>\n<\/ul>\n<p>Here\u2019s a concrete example:<\/p>\n<p><codeswift>let cannon = IonCannon()<br \/>\ncannon.fireBurstOf(5)                   \/\/ Will fire 5 ion pulses<br \/>\ncannon.fireBurstOf(5, numberOfTimes: 1) \/\/ Will also fire 5 ion pulses<br \/>\ncannon.fireBurstOf(5, numberOfTimes: 2) \/\/ Will fire 10 ion pulses<\/codeswift><\/p>\n<h3>Type Methods<\/h3>\n<p>As well as instance methods, you can also define methods that belong to the class itself rather than an instance of the class. Such methods are known as <strong><em>type methods<\/em><\/strong> and are specified by placing the <code>static<\/code> keyword before the method\u2019s <code>func<\/code> keyword.<\/p>\n<div class=\"zilla-alert white\"> Those familiar with object-oriented languages such as Java and ActionScript 3 will be familiar with the concept of static methods. A type method is Swift\u2019s equivalent of a static method. <\/div>\n<p>Let\u2019s work through a simple example. We\u2019ll write a type method within our <codeswift>IonCannon<\/codeswift> class that returns a text description stating how well the Rebel Alliance are faring against the Galactic Empire. The description will be generated based on the number of Star Destroyers that have been successfully hit by <strong>all<\/strong> ion cannon instances.<\/p>\n<p>Start by adding a type property that keeps track of the number of Star Destroyers that have been successfully hit by our ion cannons:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;<codeswiftbold>static var directHits = 0<\/codeswiftbold><br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;:<br \/>\n&nbsp;&nbsp;:<br \/>\n}<\/codeswift><\/p>\n<p>We\u2019ll also add a few lines to our <codeswift>fireBurstOf(_:numberOfTimes:)<\/codeswift> method so that it randomly attempts to increment the <codeswift>directHits<\/codeswift> type property each time an ion pulse is fired. Update your method to look like this: <\/p>\n<p><codeswift><codeswiftbold>import Foundation<\/codeswiftbold><br \/>\n&nbsp;<br \/>\nclass IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition = IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;static var directHits = 0<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;:<br \/>\n&nbsp;&nbsp;:<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func fireBurstOf(amount: Int, numberOfTimes: Int = 1) -&gt; Int {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;var remainingShots = amount * numberOfTimes<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;var actuallyFired = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;while ammunition &gt; 0 &#038;&#038; remainingShots &gt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;remainingShots&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actuallyFired++<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<codeswiftbold>if arc4random_uniform(10) == 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IonCannon.directHits++<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return actuallyFired<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Notice on the first line of code above that we imported iOS\u2019s Foundation library. Doing so provides support for random number generation via the <codeswift>arc4random_uniform(_:)<\/codeswift> global function.<\/p>\n<p>Finally, we\u2019ll add our type method to the class. This method will examine the <codeswift>directHits<\/codeswift> type property and return a text description based on the number of Star Destroyers that have been successfully hit by <strong>all<\/strong> ion cannon instances. Add the following method at the end of your class:<\/p>\n<p><codeswift>static func report() -&gt; String {<br \/>\n&nbsp;&nbsp;switch directHits {<br \/>\n&nbsp;&nbsp;case 0&#46;&#46;&#46;2:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;The rebel fleet has little chance&#8221;<br \/>\n&nbsp;&nbsp;case 3&#46;&#46;&#46;5:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;Some rebel transports may get away from Hoth&#8221;<br \/>\n&nbsp;&nbsp;default:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;The entire rebel fleet will likely escape&#8221;<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>And here\u2019s how we\u2019d use our updated class:<\/p>\n<p><codeswift>let cannon1 = IonCannon()<br \/>\nlet cannon2 = IonCannon()<br \/>\nlet cannon3 = IonCannon()<br \/>\ncannon1.fireBurstOf(5, numberOfTimes: 3)<br \/>\ncannon2.fireBurstOf(12)<br \/>\ncannon3.fireBurstOf(7, numberOfTimes: 2)<br \/>\nprint(IonCannon.report())<\/codeswift><\/p>\n<p>The code above creates three ion cannon instances and fires off a burst of ion pulses from each. We then obtain a report to see if the cannon fire was enough to clear the Empire\u2019s Star Destroyers from the path of the fleeing Rebel fleet.<\/p>\n<p>Pay particular attention to how we call the <codeswift>report<\/codeswift> method. Since it\u2019s a type method we make a call directly on the class rather than an instance of the class. Here\u2019s the call again:<\/p>\n<p><codeswift>IonCannon.report()<\/codeswift><\/p>\n<p>We can also find out the actual number of direct hits by obtaining the value of the class\u2019 <codeswift>directHits<\/codeswift> type property:<\/p>\n<p><codeswift>print(IonCannon.directHits)<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> You can also use the <code>class<\/code> keyword in place of <code>static<\/code> when defining a type method. Doing so will allow a subclass to override the superclass\u2019 implementation of the type method. This will be covered at a later date in part five. <\/div>\n<h3>Initializers<\/h3>\n<p>In <a href=\"?p=999\" target=\"_blank\">part three<\/a> we covered initialization of structures including how to write custom initializers. In this tutorial we have seen that class instances are created using initializer syntax similar to structure initialization:<\/p>\n<p><codeswift>let cannon = IonCannon()<\/codeswift><\/p>\n<p>We can also write one or more custom initializer methods for a class, which can be called to create a new instance of a particular class. Custom initializers are useful when certain stored properties of an instance need to be set or any further setup within the instance is required.<\/p>\n<div class=\"zilla-alert white\"> If you have a background in object-oriented programming languages such as Java, C++, or ActionScript 3 then you\u2019ll be familiar with class constructors. Initializers in Swift perform the same role. <\/div>\n<p>An initializer is required if a default value has not been assigned to all of a class\u2019 stored properties. The only exception to this are optional property types, which can be assigned a value at a later point.<\/p>\n<p>Here\u2019s how our <codeswift>IonCannon<\/codeswift> class might look if its <codeswift>ammunition<\/codeswift> property had not been assigned a default value along with its declaration:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition <codeswiftbold>:Int<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;static var directHits = 0<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;<codeswiftbold>init() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;:<br \/>\n&nbsp;&nbsp;:<br \/>\n}<\/codeswift><\/p>\n<p>In the example above we set the initial value of our <codeswift>ammunition<\/codeswift> property within an initializer. Of course, if your class\u2019 stored properties always take the same initial value then you really should provide a default value rather than write an initialiser.<\/p>\n<div class=\"zilla-alert white\"> If you\u2019re an Objective-C developer then you\u2019ll already be familiar with initialisers. However, unlike Objective-C, Swift initialisers do not explicitly return a value. <\/div>\n<p>A more practical use of initializers is when you wish to customise the initialization of a class instance with input parameters. Let\u2019s improve our <codeswift>IonCannon<\/codeswift> class so that we can set the cannon\u2019s initial amount of ammunition during initialization:<\/p>\n<p><codeswift>class IonCannon {<br \/>\n&nbsp;&nbsp;static let capacity = 20<br \/>\n&nbsp;&nbsp;var ammunition <codeswiftbold>= IonCannon.capacity<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ammunition &lt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else if ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;static var directHits = 0<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;<codeswiftbold>init(withAmmunition ammunition: Int = IonCannon.capacity) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.ammunition = ammunition<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;if self.ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func reload() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;func fireBurstOf(amount: Int, numberOfTimes: Int = 1) -&gt; Int {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;var remainingShots = amount * numberOfTimes<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;var actuallyFired = 0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;while ammunition &gt; 0 &#038;&#038; remainingShots &gt; 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ammunition&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;remainingShots&#8211;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actuallyFired++<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if arc4random_uniform(10) == 0 {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IonCannon.directHits++<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return actuallyFired<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;&nbsp;static func report() -&gt; String {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;switch directHits {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;case 0&#46;&#46;&#46;2:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;The rebel fleet has little chance&#8221;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;case 3&#46;&#46;&#46;5:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;Some rebel transports may get away from Hoth&#8221;<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;default:<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return &#8220;The entire rebel fleet will likely escape&#8221;<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Our custom initialiser takes a single parameter that is used to set the instance\u2019s initial amount of ammunition. The initialiser\u2019s body also safeguards against invalid values by ensuring that the specified ammunition value isn\u2019t a negative integer or greater than the cannon\u2019s capacity.<\/p>\n<p>Also, our initialiser has both a local (<codeswift>ammunition<\/codeswift>) and an external (<codeswift>withAmmunition<\/codeswift>) parameter name. As with functions and methods, the local name is used within the initialiser\u2019s body, while the external name is used when calling the initialiser. The external parameter name is particularly important when calling initialisers since they do not have an identifying function name before their parentheses in the same way that functions and methods do.<\/p>\n<p>Finally, you should note that our custom initialiser\u2019s parameter also has a default value of <codeswift>IonCannon.capacity<\/codeswift> specified. Without this we\u2019d need to write a second initialiser that accepted no parameters and simply initialised the <codeswift>ammunition<\/codeswift> property to a default value.<\/p>\n<p>With our initialiser in place, we can now create ion cannon instances and provide each with a specified initial amount of ammunition. Here are some concrete examples:<\/p>\n<p><codeswift>let cannon1 = IonCannon()<br \/>\nlet cannon2 = IonCannon(withAmmunition: 15)<br \/>\nlet cannon3 = IonCannon(withAmmunition: 40)<\/codeswift><\/p>\n<h3>The Self Property<\/h3>\n<p>We\u2019ve mentioned the <code>self<\/code> property before when covering structures, but for the avoidance of doubt we\u2019ll spend a few moments with it again.<\/p>\n<p>Just like structures, every class instance has an implicit property named <codeswift>self<\/codeswift>. This property refers to the current instance within its own methods and can be used to refer to a property or method of that instance. As an example, take a look at our class\u2019 <codeswift>reload<\/codeswift> method:<\/p>\n<p><codeswift>func reload() {<br \/>\n&nbsp;&nbsp;ammunition = IonCannon.capacity<br \/>\n}<\/codeswift><\/p>\n<p>We can rewrite this method to explicitly use <codeswift>self<\/codeswift> when referring to our instance\u2019s <codeswift>ammunition<\/codeswift> property. Here\u2019s how it would look:<\/p>\n<p><codeswift>func reload() {<br \/>\n&nbsp;&nbsp;<codeswiftbold>self.<\/codeswiftbold>ammunition = IonCannon.capacity<br \/>\n}<\/codeswift><\/p>\n<p>However, for most situations you won\u2019t need to explicitly use <codeswift>self<\/codeswift>. Swift will simply assume that you are referring to a property or method of the current instance.<\/p>\n<p>The <codeswift>self<\/codeswift> property is useful when a parameter name of a method is the same as a property of the instance. In such situations the parameter name takes precedence and the property can only be referred to via <codeswift>self<\/codeswift>. We can actually see this in our class\u2019 initialiser, where its internal parameter has the same name as the class\u2019 <codeswift>ammunition<\/codeswift> property. To remove any ambiguity, the <codeswift>self<\/codeswift> prefix was used to identify the property:<\/p>\n<p><codeswift>init(withAmmunition <codeswiftbold>ammunition<\/codeswiftbold>: Int = IonCannon.capacity) {<br \/>\n&nbsp;&nbsp;<codeswiftbold>self.<\/codeswiftbold>ammunition = <codeswiftbold>ammunition<\/codeswiftbold><br \/>\n&nbsp;&nbsp;if <codeswiftbold>self.<\/codeswiftbold>ammunition &gt; IonCannon.capacity {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;<codeswiftbold>self.<\/codeswiftbold>ammunition = IonCannon.capacity<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> Objective-C developers will be familiar with the <code>self<\/code> keyword. It is commonly know as <code>this<\/code> in most other programming languages. <\/div>\n<h2>Next Time<\/h2>\n<p>We\u2019ve covered the basics of object oriented programming. While Swift uses different naming conventions the principles are more-or-less identical to those found in other object-oriented languages. If you\u2019re coming from a  language such as Java, C++, TypeScript or ActionScript 3 then writing and working with classes in Swift should be straight forward. Even if you&#8217;re coming from JavaScript, which lacks much of the syntactic sugar that other object-oriented languages provide, you shouldn\u2019t find things too much of a stretch to grasp.<\/p>\n<p>There are still a few object-oriented features still to cover. Next time we\u2019ll spend some time looking at inheritance. You may also have noticed that we haven\u2019t yet covered access control. Swift\u2019s access control is different from that found in most languages &#8211; it is file-based rather than class-based &#8211; and therefore deserves more space than this particular tutorial can afford it. Finally, we\u2019ll also spend some time looking at class deinitialization, which allows us to perform any manual clean-up when a class instance is no longer needed.<\/p>\n<p>See you in part five.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to the fourth tutorial in the series. Today we\u2019ll cover many of Swift\u2019s object-oriented features. What you will learn&#8230; Basic object-oriented concepts with Swift What you should know&#8230; A familiarity with object-oriented programming concepts The basics of the Swift programming language from part one, two and three Swift doesn\u2019t favour one programming paradigm over [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"footnotes":""},"categories":[13],"tags":[],"class_list":["post-1014","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"_links":{"self":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/1014","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1014"}],"version-history":[{"count":50,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/1014\/revisions"}],"predecessor-version":[{"id":1103,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/1014\/revisions\/1103"}],"wp:attachment":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1014"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1014"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1014"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}