{"id":999,"date":"2015-01-22T20:06:18","date_gmt":"2015-01-22T20:06:18","guid":{"rendered":"http:\/\/www.yeahbutisitswift.com\/?p=999"},"modified":"2015-05-28T19:12:37","modified_gmt":"2015-05-28T19:12:37","slug":"quick-start-guide-to-swift-part-3","status":"publish","type":"post","link":"http:\/\/www.yeahbutisitswift.com\/?p=999","title":{"rendered":"Quick Start Guide to Swift: Part 3"},"content":{"rendered":"<p>Welcome to the third tutorial in the series. Here we will cover functions and structures. This will put us in good stead for part four where we&#8217;ll finally get onto the subject of object-oriented programming.<\/p>\n<h3>What you will learn&#8230;<\/h3>\n<ul>\n<li>How to define and call functions<\/li>\n<li>How to work with structures<\/li>\n<\/ul>\n<h3>What you should know&#8230;<\/h3>\n<ul>\n<li>The basics of the Swift programming language from <a href=\"?p=522\" target=\"_blank\">part one<\/a> and <a href=\"?p=324\" target=\"_blank\">two<\/a><\/li>\n<\/ul>\n<p>During this series we&#8217;ve used several global functions provided by Swift, such as <code>println<\/code> and <code>count<\/code>. Now we&#8217;ll see how to write our own custom functions in order to build modular code that can accomplish specific tasks. We&#8217;ll also spend considerable time exploring structures, which will effectively let you define your own custom types within Swift.<\/p>\n<p>Functions and structures are both large topics and we certainly won&#8217;t cover every aspect of them here. However, both lead very nicely into the subject of object-oriented programming and therefore deserve particular attention before we can begin to work with classes in part four.<\/p>\n<p><!--more--><\/p>\n<h2>Getting Started<\/h2>\n<p>By now you should feel comfortable with the content covered in the first two 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<\/ul>\n<p>To try out this tutorial&#8217;s code examples, install Xcode 6 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>Functions<\/h2>\n<p>We&#8217;ll begin by writing the simplest form of function: one that takes no parameters and doesn&#8217;t return anything. The <code>func<\/code> keyword is used to define a function:<\/p>\n<p><codeswift>func greetJedi() {<br \/>\n&nbsp;&nbsp;println(&quot;Greetings Master Jedi!&quot;)<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> Convention in Swift (as it is in many other languages) dictates that functions use <a href=\"http:\/\/en.wikipedia.org\/wiki\/CamelCase\" target=\"_blank\">lowerCamelCase<\/a> names. For example, <code>greetJedi<\/code> rather than <code>GreetJedi<\/code> or <code>greetjedi<\/code>. <\/div>\n<p>The code above defines a function named <code>greetJedi<\/code>. Enter it into your playground then call the function by typing:<\/p>\n<p><codeswift>greetJedi()<\/codeswift><\/p>\n<p>This will result in the following message being displayed within the sidebar:<\/p>\n<p><codeswift>Greetings Master Jedi!<\/codeswift><\/p>\n<h3>Parameters<\/h3>\n<p>You can optionally define one or more typed parameters for your function. Here&#8217;s an alternative version of the <code>greetJedi<\/code> function that takes a Jedi&#8217;s name as a parameter:<\/p>\n<p><codeswift>func greetJedi(name: String) {<br \/>\n&nbsp;&nbsp;println(&quot;Greetings Master \\(name)!&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Now you can pass a name as an argument to the <code>greetJedi<\/code> function:<\/p>\n<p><codeswift>greetJedi(&quot;Obi-Wan Kenobi&quot;)<\/codeswift><\/p>\n<p>The line above will result in the following being printed to the appropriate output:<\/p>\n<p><codeswift>Greetings Master Obi-Wan Kenobi!<\/codeswift><\/p>\n<p>Let&#8217;s write another version of <code>greetJedi<\/code> that takes two parameters: a forename and a surname.<\/p>\n<p><codeswift>func greetJedi(forename: String, surname: String) {<br \/>\n&nbsp;&nbsp;println(&quot;Greetings Master \\(forename)!&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Here are a few examples of our <code>greetJedi<\/code> function being called:<\/p>\n<p><codeswift>greetJedi(&quot;Obi-Wan&quot;, &quot;Kenobi&quot;)<br \/>\ngreetJedi(&quot;Qui-Gon&quot;, &quot;Jinn&quot;)<\/codeswift><\/p>\n<p>Our function actually ignores the second argument and only prints the Jedi&#8217;s forename. The two calls above will result in the following being displayed:<\/p>\n<p><codeswift>Greetings Master Obi-Wan!<br \/>\nGreetings Master Qui-Gon!<\/codeswift><\/p>\n<h3>Return Values<\/h3>\n<p>You can also define a type of value that will be returned from your function. This is done by placing the <em>return arrow<\/em> <code>-&gt;<\/code> and the name of the type to return immediately after your function&#8217;s list of parameters. Here&#8217;s an example:<\/p>\n<p><codeswift>func greetJedi(forename: String, surname: String) <codeswiftbold>-> String<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;return &quot;Greetings Master \\(forename)!&quot;<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> If you&#8217;re coming from a language such as Objective-C or C, where the return type is listed first in a function&#8217;s declaration, then you may find the order of Swift&#8217;s return type a little off putting. However, persevere and I promise you&#8217;ll grow to like it.<\/p>\n<p>Of course, ActionScript and TypeScript developers will already find this syntax familiar as both languages deal with return types in a similar manner to Swift. <\/div>\n<p>The latest version of our <code>greetJedi<\/code> function now takes two parameters (a forename and surname) and returns a <code>String<\/code> that represents a greeting: previous incarnations of <code>greetJedi<\/code> had simply written the greeting directly to the appropriate output. Let&#8217;s see a few examples, where <code>greetJedi<\/code> is called, and the string it returns is output via the <code>println<\/code> function:<\/p>\n<p><codeswift>println(greetJedi(&quot;Obi-Wan&quot;, &quot;Kenobi&quot;))<br \/>\nprintln(greetJedi(&quot;Anakin&quot;, &quot;Skywalker&quot;))<br \/>\nprintln(greetJedi(&quot;Qui-Gon&quot;, &quot;Jinn&quot;))<br \/>\n<\/codeswift><\/p>\n<p>This would result in the following being displayed in the sidebar of your playground:<\/p>\n<p><codeswift>Greetings Master Obi-Wan!<br \/>\nGreetings Master Anakin!<br \/>\nGreetings Master Qui-Gon<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> It&#8217;s beneficial to know that <strong>all<\/strong> functions actually return a value, even those that do not explicitly define one. Functions without a defined return type actually return a special value of type <code>Void<\/code>. This is simply an empty tuple, which can also be written as <code>()<\/code>.<\/p>\n<p>Take this function for example:<\/p>\n<p><codeswift>func saySomething() {<br \/>\n&nbsp;&nbsp;println(&quot;Hullo World!&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Although there is no need to do so, it could also be written as:<\/p>\n<p><codeswift>func saySomething() <codeswiftbold>-> ()<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;println(&quot;Hullo World!&quot;)<br \/>\n}<\/codeswift> <\/div>\n<h3>Returning Tuples<\/h3>\n<p>If you wish to return more than one value from a function then consider returning a tuple. The following example takes an array of names and returns the first and last name from the array:<\/p>\n<p><codeswift>func getFirstAndLast(names: [String]) -> (first: String, last: String) {<br \/>\n&nbsp;&nbsp;return (names[0], names[names.count &#8211; 1])<br \/>\n}<\/codeswift><br \/>\n<codeswift><br \/>\nlet names = [&quot;Luke&quot;, &quot;Ben&quot;, &quot;Anakin&quot;, &quot;Yoda&quot;]<br \/>\nlet result = getFirstAndLast(names)<br \/>\nprintln(&quot;\\(result.first) and \\(result.last)&quot;)<\/codeswift><\/p>\n<p>The code snippet above will print the following in your playground&#8217;s sidebar:<\/p>\n<p><codeswift>Luke and Yoda<\/codeswift><\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> Our <code>getFirstAndLast<\/code> function above isn&#8217;t particularly robust. If you pass an empty array to it you&#8217;ll receive an error.<\/p>\n<p>Re-write the function to safeguard against this by returning <code>nil<\/code> when there are fewer than two names within the array. You&#8217;ll need to return an optional tuple to achieve this. <\/div><\/div>\n<h3>Local and External Parameter Names<\/h3>\n<p>Most of the functions we&#8217;ve written so far have defined parameter names. These names are <strong><em>local parameters<\/em><\/strong> however and can only be used within the function&#8217;s body.<\/p>\n<p>With Swift you can also define <strong><em>external parameter names<\/em><\/strong>, which are used when calling the function and help to clarify the purpose of each parameter. When defining a function, the parameter&#8217;s external name is placed directly before its local name.<\/p>\n<p>Here&#8217;s our <code>greetJedi<\/code> function but with an external name defined for each parameter:<\/p>\n<p><codeswift>func greetJedi(<codeswiftbold>forename<\/codeswiftbold> forename: String, <codeswiftbold>surname<\/codeswiftbold> surname: String) -> String {<br \/>\n&nbsp;&nbsp;return &quot;Greetings Master \\(forename)!&quot;<br \/>\n}<\/codeswift><\/p>\n<p>And here is the function being called:<\/p>\n<p><codeswift>greetJedi(<codeswiftbold>forename:<\/codeswiftbold> &quot;Luke&quot;, <codeswiftbold>surname:<\/codeswiftbold> &quot;Skywalker&quot;)<\/codeswift><\/p>\n<p>As a comparison, here&#8217;s how the call looked before external parameter names were defined:<\/p>\n<p><codeswift>greetJedi(&quot;Luke&quot;, &quot;Skywalker&quot;)<\/codeswift><\/p>\n<p>If an external name is defined for a parameter then it <strong>must<\/strong> be used when calling its function.<\/p>\n<p>In the example above, our external parameter names were identical to the function&#8217;s local parameter names, however they can be different. Here&#8217;s another example to illustrate this:<\/p>\n<p><codeswift>func setPoint(<codeswiftbold>atX<\/codeswiftbold> x: Float, <codeswiftbold>andY<\/codeswiftbold> y: Float) {<br \/>\n&nbsp;&nbsp;\/\/ Implementation goes here<br \/>\n}<\/codeswift><\/p>\n<p><codeswift>setPoint(atX: 10.5 andY: 15.25)<\/codeswift><\/p>\n<p>As an alternatively we can alter the function&#8217;s name and apply an external name to just the second parameter:<\/p>\n<p><codeswift>func <codeswiftbold>setPointAtX<\/codeswiftbold>(x: Float, <codeswiftbold>andY<\/codeswiftbold> y: Float) {<br \/>\n&nbsp;&nbsp;\/\/ Implementation goes here<br \/>\n}<\/codeswift><\/p>\n<p><codeswift>setPointAtX(10.5, andY: 15.25)<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> If you&#8217;re an Objective-C developer then external parameter names should help provide the same level of expressiveness that you&#8217;re used to when defining and calling Objective-C methods. <\/div>\n<p>If you wish to provide an external parameter name that is identical to the function&#8217;s local parameter name then there is no need to write the same name twice. Instead you can prefix your local parameter with a hash symbol (<code>#<\/code>). By using this shorthand external parameter name syntax, we can change our <code>greetJedi<\/code> function from:<\/p>\n<p><codeswift>func greetJedi(forename forename: String, surname surname: String) -> String {<br \/>\n&nbsp;&nbsp;return &quot;Greetings Master \\(forename)!&quot;<br \/>\n}<\/codeswift><\/p>\n<p>to this:<\/p>\n<p><codeswift>func greetJedi(<codeswiftbold>#<\/codeswiftbold>forename: String, <codeswiftbold>#<\/codeswiftbold>surname: String) -> String {<br \/>\n&nbsp;&nbsp;return &quot;Greetings Master \\(forename)!&quot;<br \/>\n}<\/codeswift><\/p>\n<h3>Default Parameter Values<\/h3>\n<p>A default value can be assigned to a function&#8217;s parameter. Any parameters with a default value should be placed at the end of the function&#8217;s parameter list. Here&#8217;s an example where the <code>energy<\/code> parameter is defaulted to <code>50<\/code>:<\/p>\n<p><codeswift>func describeJedi(name: String, energy: Int <codeswiftbold>= 50<\/codeswiftbold>) -> String {<br \/>\n&nbsp;&nbsp;var description = &quot;\\(name) is &quot;<br \/>\n&nbsp;&nbsp;if energy < 40 {\n&nbsp;&nbsp;&nbsp;&nbsp;description += &quot;weak.&quot;\n&nbsp;&nbsp;} else if energy < 80 {\n&nbsp;&nbsp;&nbsp;&nbsp;description += &quot;an average Jedi.&quot;\n&nbsp;&nbsp;} else {\n&nbsp;&nbsp;&nbsp;&nbsp;description += &quot;a powerful Jedi.&quot;\n&nbsp;&nbsp;}<\/codeswift><br \/>\n<codeswift><br \/>\n&nbsp;&nbsp;return description<br \/>\n}<\/codeswift><\/p>\n<p>The following call:<\/p>\n<p><codeswift>describeJedi(&quot;Luke Skywalker&quot;)<\/codeswift><\/p>\n<p>Will return <code>Luke Skywalker is an average Jedi.<\/code> (he&#8217;s actually an awesome Jedi: this is just a silly example remember) Because the function call&#8217;s second argument was omitted, a default value of <code>50<\/code> was used.<\/p>\n<p>Of course, you can explicitly specify the second argument:<\/p>\n<p><codeswift>describeJedi(&quot;Yoda&quot;, <codeswiftbold>energy: 100<\/codeswiftbold>)<\/codeswift><\/p>\n<p>Notice the use of the second parameter&#8217;s external name in the call above. You may have spotted that we didn&#8217;t actually define an external name for this parameter. For parameters with default values, Swift automatically assigns an external name that matches the parameter&#8217;s local name. You can of course, explicitly assign an external parameter name of your own choosing. Alternatively you can opt-out of Swift&#8217;s default behaviour by placing an underscore (<codeswift>_<\/codeswift>) where the external parameter name would normally be. Here&#8217;s an example:<\/p>\n<p><codeswift>func describeJedi(name: String, <codeswiftbold>_<\/codeswiftbold> energy: Int = 50) -> String {<br \/>\n&nbsp;&nbsp;\/\/ Implementation goes here<br \/>\n}<\/codeswift><\/p>\n<p>Your call to <code>describeJedi<\/code> would now look like this:<\/p>\n<p><codeswift>describeJedi(&quot;Yoda&quot;, 100)<\/codeswift><\/p>\n<h3>Variadic Parameters<\/h3>\n<p>Swift provides support for variadic parameters. A function can have at most one variadic parameter, which accepts zero or more values of a specified type. Variadic parameters are ideal when writing a function that can be passed a varying number of input values. Place three period characters (<codeswift>&#8230;<\/codeswift>) directly after a parameter&#8217;s type to indicate that it is a variadic parameter:<\/p>\n<p><codeswift>func averageStarfightersLost(numbers: Int<codeswiftbold>..&#46;<\/codeswiftbold>) -> Double {<br \/>\n&nbsp;&nbsp;var total: Double = 0<br \/>\n&nbsp;&nbsp;for number in numbers {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;total += Double(number)<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;return total \/ Double(numbers.count)<br \/>\n}<\/codeswift><\/p>\n<p>The function above is used to determine the average number of starfighters the Rebel Alliance lose during space battles. It accepts a list of integers, where each integer represents the number of fighters lost in a particular battle.<\/p>\n<p>Each of the values passed to a variadic parameter are made available within the function as an array of the appropriate type. In the example above, the number of starfighters lost in each battle are made available as an array of integers. The array uses the variadic parameter&#8217;s name (in this case <code>numbers<\/code>).<\/p>\n<p>When calling <code>averageStarfightersLost<\/code>, each of the integers passed should be separated by a comma. Here are a few examples:<\/p>\n<p><codeswift>var avg = averageStarfightersLost(10, 5, 0, 4, 1, 0, 0, 6)<br \/>\nprintln(&quot;The rebel&#8217;s are losing \\(avg) X-wings per battle.&quot;)<\/codeswift><br \/>\n<codeswift><br \/>\navg = averageStarfightersLost(20, 15, 4, 0, 8)<br \/>\nprintln(&quot;The rebel&#8217;s are losing \\(avg) Y-wings per battle.&quot;)<\/codeswift><\/p>\n<p>If your function has more than one parameter, and one of those parameters is a variadic parameter, then place the variadic parameter last in the parameter list. This is also the case even if some of your other parameters have been assigned default values.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> As stated, a variadic parameter can accept zero or more input values. Our <code>averageStarfightersLost<\/code> function however seems to have a problem when zero input values are passed to it: it returns <code>(nan)<\/code> instead of the value <code>0.0<\/code>.<\/p>\n<p>See if you can identify why this is and make a fix to your function to ensure that <code>0.0<\/code> is returned when the following call is made:<\/p>\n<p><code>avg = averageStarfightersLost()<\/code> <\/div><\/div>\n<h3>Constant and Variable Parameters<\/h3>\n<p>Unlike many languages, parameters in Swift are constants by default. Take the following example:<\/p>\n<p><codeswift>func describeJedi(name: String, energy: Int) -> String {<br \/>\n&nbsp;&nbsp;name += &quot; has an energy of \\(energy)&quot;<br \/>\n&nbsp;&nbsp;return name<br \/>\n}<\/codeswift><\/p>\n<p>It will return the following compile-time error: <code>Cannot assign to 'let' value 'name'<\/code>.<\/p>\n<p>If you want to change the value of a parameter within the body of your function then you must explicitly specify that parameter as a <strong><em>variable parameter<\/em><\/strong> by prefixing it with the <code>var<\/code> keyword:<\/p>\n<p><codeswift>func describeJedi(<codeswiftbold>var<\/codeswiftbold> name: String, energy: Int) -> String {<br \/>\n&nbsp;&nbsp;name += &quot; has an energy of \\(energy)&quot;<br \/>\n&nbsp;&nbsp;return name<br \/>\n}<\/codeswift><\/p>\n<p>Now the <code>name<\/code> parameter&#8217;s value can be modified within the body of your function.<\/p>\n<h3>In-Out Parameters<\/h3>\n<p>Variable parameters can only be changed within a function&#8217;s body. Changes in value do not persist outside of the function. If you want a change to a parameter&#8217;s value to persist after the function call has taken place then define the parameter as an <strong><em>in-out parameter<\/em><\/strong>.<\/p>\n<p>To specify an in-out parameter, place the <code>inout<\/code> keyword at the beginning of the parameter&#8217;s definition:<\/p>\n<p><codeswift>func swapLightsabers(<codeswiftbold>inout<\/codeswiftbold> lightsaber1: String, <codeswiftbold>inout<\/codeswiftbold> lightsaber2: String) {<br \/>\n&nbsp;&nbsp;let temp: String = lightsaber1<br \/>\n&nbsp;&nbsp;lightsaber1 = lightsaber2<br \/>\n&nbsp;&nbsp;lightsaber2 = temp<br \/>\n}<\/codeswift><\/p>\n<p>The function above takes two string parameters that each represent the colour of a Jedi&#8217;s lightsaber, and swaps them. After the function has executed, the first lightsaber will have the colour of the second lightsaber and vice versa. Here&#8217;s how to call <code>swapLightsabers<\/code>:<\/p>\n<p><codeswift><codeswiftbold>var lukesLightsaber = &quot;blue&quot;<br \/>\nvar yodasLightsaber = &quot;green&quot;<\/codeswiftbold><br \/>\nprintln(&quot;Luke&#8217;s lightsaber is \\(lukesLightsaber)&quot;)<br \/>\nprintln(&quot;Yoda&#8217;s lightsaber is \\(yodasLightsaber)&quot;)<\/codeswift><br \/>\n<codeswift><br \/>\n<codeswiftbold>swapLightsabers(&#038;lukesLightsaber, &#038;yodasLightsaber)<\/codeswiftbold><br \/>\nprintln(&quot;Luke&#8217;s lightsaber is now \\(lukesLightsaber)&quot;)<br \/>\nprintln(&quot;Yoda&#8217;s lightsaber is now \\(yodasLightsaber)&quot;)<\/codeswift><\/p>\n<p>Typing the above into your playground file will result in the following being output:<\/p>\n<p><codeswift>Luke&#8217;s lightsaber is blue<br \/>\nYoda&#8217;s lightsaber is green<br \/>\nLuke&#8217;s lightsaber is now green<br \/>\nYoda&#8217;s lightsaber is now blue<\/codeswift><\/p>\n<p>Notice in the example above that two variables (<code>lukesLightsaber<\/code> and <code>yodasLightsaber<\/code>) are passed as arguments to the <code>swapLightsabers<\/code> function. You cannot pass a constant or a literal value as an argument since their values cannot be modified. Also notice that an ampersand (<codeswift>&#038;<\/codeswift>) needs to be placed directly before the variable&#8217;s name when passing it as an argument to an in-out parameter.<\/p>\n<p>The point to take from this example is that the function doesn&#8217;t return anything. By specifying both parameters as in-out parameters, the changes are made directly to the variables (<code>lukesLightsaber<\/code> and <code>yodasLightsaber<\/code>) that are passed in as arguments to our function.<\/p>\n<h2>Structs<\/h2>\n<p>If you&#8217;re from an Objective-C or C background then you&#8217;ll be familiar with structures (often referred to as structs). In fact, unlike some languages, structures in Swift share many of the powerful capabilities you&#8217;d normally associate with classes.<\/p>\n<p>If on the other hand, you develop with an ECMAScript-based language such as JavaScript or ActionScript then you may not have come across structures. However, they aren&#8217;t difficult to grasp.<\/p>\n<p>A structure is declared using the <code>struct<\/code> keyword and its definition is placed within a pair of braces. Its general form looks like this:<\/p>\n<p><codeswift>struct StructName {<br \/>\n&nbsp;&nbsp;\/\/ Implementation goes here<br \/>\n}<\/codeswift><\/p>\n<p>Here&#8217;s a concrete example of a structure that represents a two-dimensional point:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x = 0.0, y = 0.0<br \/>\n}<\/codeswift><\/p>\n<p>This struct contains two <strong><em>stored properties<\/em><\/strong> named <code>x<\/code> and <code>y<\/code>. Both are variables of type <code>Double<\/code> and have default values of <code>0.0<\/code>.<\/p>\n<h3>Instantiating a Struct<\/h3>\n<p>To use a structure you must create an instance of it using initializer syntax. Here&#8217;s an example where we instantiate our <code>Point<\/code> structure:<\/p>\n<p><codeswift>var target = Point()<\/codeswift><\/p>\n<p>This creates a variable named <code>target<\/code> that represents a <code>Point<\/code> instance. The instance&#8217;s <code>x<\/code> and <code>y<\/code> properties are set to their default value of <code>0.0<\/code>.<\/p>\n<p>Structures also provide a <strong><em>memberwise initializer<\/em><\/strong>, which can be used to initialise each of the structure&#8217;s stored properties:<\/p>\n<p><codeswift>var target = Point(x: 64, y: 12.5)<\/codeswift><\/p>\n<p>The snippet above instantiates an instance that has a default <code>x<\/code> value of <code>64<\/code> and a default <code>y<\/code> value of <code>12.5<\/code>. You must provide a value for every one of the structure&#8217;s stored properties. Take a look at the following:<\/p>\n<p><codeswift>var target = Point(x: 64)<\/codeswift><\/p>\n<p>This will result in the following compile-time error: <code>Missing argument for parameter 'y' in call<\/code>.<\/p>\n<h3>Accessing Properties<\/h3>\n<p>You can access and modify an instance&#8217;s stored properties using <strong><em>dot syntax<\/em><\/strong>. The code snippet below shows how to query the value of your <code>Point<\/code> instance&#8217;s <code>x<\/code> and <code>y<\/code> properties:<\/p>\n<p><codeswift>var target = Point()<br \/>\nvar x = <codeswiftbold>target.x<\/codeswiftbold><br \/>\nvar y = <codeswiftbold>target.y<\/codeswiftbold><\/codeswift><\/p>\n<p>Here&#8217;s how you assign new values to your instance&#8217;s stored properties:<\/p>\n<p><codeswift>target.x = 34.5<br \/>\ntarget.y = 10.0<\/codeswift><\/p>\n<h3>Structs are Value Types<\/h3>\n<p>Every type we&#8217;ve looked at in this series is what is known as a <strong><em>value type<\/em><\/strong>. Structs are no different.<\/p>\n<p>A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed as an argument to a function. This can best be illustrated with the following example:<\/p>\n<p><codeswift>var point1 = Point(x: 64, y: 32)<br \/>\nvar point2 = point1<\/codeswift><\/p>\n<p>The code above creates an instance of a <code>Point<\/code> structure and assigns it to a variable named <code>point1<\/code>. A second variable named <code>point2<\/code> is then created and it is set to equal <code>point1<\/code>.<\/p>\n<p>Now take a look at the following few lines of code:<\/p>\n<p><codeswift>point1.x = 128<br \/>\nprintln(&quot;point1.x: \\(point1.x)&quot;)<br \/>\nprintln(&quot;point2.x: \\(point2.x)&quot;)<\/codeswift><\/p>\n<p>Those from an ECMAScript background may reasonably expect that any changes to the properties of <code>point1<\/code> will also be reflected in the variable <code>point2<\/code>. In other words, they may expect the following to be displayed:<\/p>\n<p><codeswift>point1.x: 128<br \/>\npoint2.x: 128<\/codeswift><\/p>\n<p>However, since the <code>point2<\/code> variable holds its own copies of the <code>x<\/code> and <code>y<\/code> properties, the following result will actually be written to the appropriate output:<\/p>\n<p><codeswift>point1.x: 128<br \/>\npoint2.x: 64<\/codeswift><\/p>\n<p>We&#8217;ll discover in part four that classes are handled differently (they are <strong><em>reference types<\/em><\/strong>) and this can lead to some confusion since classes and structures are similar in so many ways.<\/p>\n<div class=\"zilla-alert white\"> Arrays, dictionaries, and enumerations are also value types in Swift. This may come as a surprise to many since collection types such as arrays and dictionaries are typically represented by classes in other programming languages. Swift however opts to model them as structures instead.<\/p>\n<p>The following code snippet will demonstrate this for arrays:<\/p>\n<p><codeswift>var arrayA = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br \/>\nvar arrayB = arrayA<br \/>\narrayA[0] = &quot;d&quot;<br \/>\nprintln(arrayA[0]) \/\/ Will output &#8216;d&#8217;<br \/>\nprintln(arrayB[0]) \/\/ You may expect &#8216;d&#8217; here but &#8216;a&#8217; will actually be output<br \/>\n<\/codeswift><\/p>\n<p>If you&#8217;re familiar with Objective-C then this may seem counterintuitive since <code>NSString<\/code>, <code>NSArray<\/code> and <code>NSDictionary<\/code> are all implemented as classes and are therefore reference types. <\/div>\n<h3>Custom Initialisation<\/h3>\n<p>When an instance of a structure is created, its stored properties are assigned an initial value as part of the initialisation process. All properties must have an initial value or instantiation cannot take place. One way of doing this is to set a default value when defining each property of your struct. We&#8217;ve already seen this with our <code>Point<\/code> structure:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x = 0.0, y = 0.0<br \/>\n}<br \/>\nvar target = Point()<\/codeswift><\/p>\n<p>Alternatively, you can write an <strong><em>initializer<\/em><\/strong> and set default values for each of your properties within it:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x, y<codeswiftbold>: Double<\/codeswiftbold><br \/>\n&nbsp;&nbsp;<codeswiftbold>init() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;x = 0.0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;y = 0.0<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<br \/>\nvar target = Point()<\/codeswift><\/p>\n<p>Your initializer should be named <code>init<\/code> and, unlike a regular function (or class method), isn&#8217;t preceded with the <code>func<\/code> keyword. Also notice that we had to explicitly declare the type of both properties since a variable&#8217;s type cannot be inferred unless an initial value is provided with its definition.<\/p>\n<p>Any custom initializers you write replace the struct&#8217;s default memberwise initializer. For example, the following attempt to create a <code>Point<\/code> instance with a default <code>x<\/code> value of <code>15.5<\/code> and a <code>y<\/code> value of <code>0.75<\/code> will result in an error:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x, y: Double<br \/>\n&nbsp;&nbsp;init() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;x = 0.0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;y = 0.0<br \/>\n&nbsp;&nbsp;}<br \/>\n}<br \/>\nvar target = Point(x: 15.5, y: 0.75)<\/codeswift><\/p>\n<p>The above will result in the following compile-time error: <code>Extra argument 'x' in call<\/code>.<\/p>\n<p>You can overcome this problem by creating a second initializer that accepts <strong><em>initialization parameters<\/em><\/strong>:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x, y :Double<br \/>\n&nbsp;&nbsp;init() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;x = 0.0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;y = 0.0<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;<codeswiftbold>init(x: Double, y: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.x = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.y = y<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>Notice the use of the <code>self<\/code> property, which is a reference to the instance itself. In our initializer above, <code>self<\/code> is used to distinguish between the parameters named <code>x<\/code> and <code>y<\/code>, and the class&#8217; properties of the same name.<\/p>\n<div class=\"zilla-alert white\"> Objective-C developers will be familiar with the <code>self<\/code> keyword. It is commonly known as <code>this<\/code> in most other programming languages. <\/div>\n<p>We can now create two different <code>Point<\/code> instances: one that has a default position of <code>(0, 0)<\/code> and another where you can explicitly state its initial position. You can see this below:<\/p>\n<p><codeswift>let origin = Point()<br \/>\nvar target = Point(x: 15.5, y: 0.75)<\/codeswift><\/p>\n<p>Notice that your custom initializer&#8217;s local parameters have been exposed as external parameters. Swift does this by default for all custom initializers that you write. If you prefer, you can suppress this by placing an underscore (<codeswift>_<\/codeswift>) before each of your initializer&#8217;s local parameters. Alternatively you can explicitly define your own custom external parameter names. We&#8217;ll actually do this shortly with another struct that we&#8217;ll define.<\/p>\n<p>Of course, our current <code>Point<\/code> example is rather contrived for the purpose of demonstrating custom initializers. The code example above is in fact identical to the much simpler version we saw at the beginning of this section. Here is our current version again:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x, y :Double<br \/>\n&nbsp;&nbsp;init() {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;x = 0.0<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;y = 0.0<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;init(x: Double, y: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.x = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.y = y<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>and here is the identical simplified version:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x = 0.0, y = 0.0<br \/>\n}<\/codeswift><\/p>\n<p>And with this simplified version of the <code>Point<\/code> structure we can just as easily create both a default and a custom point:<\/p>\n<p><codeswift>let origin = Point()<br \/>\nvar target = Point(x: 15.5, y: 0.75)<\/codeswift><\/p>\n<h3>Initializers and External Parameter Names<\/h3>\n<p>Let&#8217;s now look at a more practical use for custom initializers. We&#8217;ll create a new structure that represents a rectangle:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left = 0.0, top = 0.0<br \/>\n&nbsp;&nbsp;var width = 0.0, height = 0.0<br \/>\n}<\/codeswift><\/p>\n<p>The <code>Rect<\/code> struct has four properties. Its <code>left<\/code> and <code>top<\/code> properties are used to define the position of the rectangle&#8217;s top-left corner. The <code>width<\/code> and <code>height<\/code> properties are used to define the rectangle&#8217;s dimensions. Let&#8217;s create a <code>Rect<\/code> instance:<\/p>\n<p><codeswift>var rectangle = Rect(left: 0, top: 0, width: 200, height: 50)<\/codeswift><\/p>\n<p>This creates a rectangle that has its top-left corner positioned at <code>(0, 0)<\/code> and has a width of <code>200<\/code> and a height of <code>50<\/code>.<\/p>\n<p>We also have our <code>Point<\/code> struct, so let&#8217;s write a custom initializer that lets us specify our rectangle&#8217;s top-left corner using it. Here&#8217;s the code:<\/p>\n<p><codeswift>struct Point {<br \/>\n&nbsp;&nbsp;var x = 0.0, y = 0.0<br \/>\n}<\/codeswift><br \/>\n<codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top<codeswiftbold>: Double<\/codeswiftbold><br \/>\n&nbsp;&nbsp;var width, height<codeswiftbold>: Double<\/codeswiftbold><br \/>\n&nbsp;&nbsp;<codeswiftbold>init(p: Point, w: Double, h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = p.x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = p.y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>We can now utilise our <code>Point<\/code> structure when creating an instance of our <code>Rect<\/code> structure:<\/p>\n<p><codeswift>var rectangle = Rect(p: Point(x: 0, y: 0), w: 200, h: 50)<\/codeswift><\/p>\n<p>While our custom initializer certainly gets the job done, we can actually improve it. We can assign external names to each of our initializer&#8217;s parameters to make our call to it more readable. This is particularly important because initializers, unlike functions, don&#8217;t have an identifiable name associated with them that can add additional meaning. Let&#8217;s make the changes:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top: Double<br \/>\n&nbsp;&nbsp;var width, height: Double<br \/>\n&nbsp;&nbsp;init(<codeswiftbold>atPoint<\/codeswiftbold> p: Point, <codeswiftbold>withWidth<\/codeswiftbold> w: Double, <codeswiftbold>andHeight<\/codeswiftbold> h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = p.x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = p.y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>We can now create an instance with a much more natural initializer call:<\/p>\n<p><codeswift>var rectangle = Rect(atPoint: Point(x: 0, y: 0), withWidth: 200, andHeight: 50)<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> Objective-C programmers will be comfortable with this much more verbose way of calling functions. <\/div>\n<h3>Initializer Delegation<\/h3>\n<p>We saw earlier with our <code>Point<\/code> structure that we can have more than one initializer. It&#8217;s also possible for one initializer to call another to help with the initialization of an instance. Let&#8217;s modify our <code>Rect<\/code> structure to include a second initializer and also have one initializer call the other:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top: Double<br \/>\n&nbsp;&nbsp;var width, height: Double<br \/>\n&nbsp;&nbsp;<codeswiftbold>init(atX x: Double, andY y: Double, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;init(atPoint p: Point, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;<codeswiftbold>self.init(atX: p.x, andY: p.y, withWidth: w, andHeight: h)<\/codeswiftbold><br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Note the use of the <code>self<\/code> property to call one initializer from within the body of another.<\/p>\n<h3>Computed Properties<\/h3>\n<p>So far we&#8217;ve only looked at stored properties within our structures. As a reminder, a stored property is a variable or constant that is stored as part of a structure&#8217;s instance. In addition to stored properties you can also define a <strong><em>computed property<\/em><\/strong>. Computed properties do not store their own value, instead they provide a getter and setter that is used to indirectly obtain and set other stored properties.<\/p>\n<p>Take our <code>Rect<\/code> structure as an example. It has a <code>left<\/code> and <code>top<\/code> property that represents the rectangle&#8217;s top-left corner. At present there are no <code>right<\/code> and <code>bottom<\/code> properties that represent the position of the rectangle&#8217;s bottom-right corner. We could create a stored property for each, but that would mean that we&#8217;d have to remember to also update each instance&#8217;s <code>width<\/code> and <code>height<\/code> properties every time we modified the <code>right<\/code> and <code>bottom<\/code> properties respectively (or vice versa). In such situations, rather than directly storing a value for <code>right<\/code> and <code>bottom<\/code>, it makes more sense to represent them as computed properties.<\/p>\n<p>Let&#8217;s begin by defining a <code>right<\/code> computed property and writing a getter and setter for it:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top: Double<br \/>\n&nbsp;&nbsp;var width, height: Double<br \/>\n&nbsp;&nbsp;<codeswiftbold>var right: Double {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return left + width<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;set(newRight) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width = newRight &#8211; left<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;init(atX x: Double, andY y: Double, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;init(atPoint p: Point, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.init(atX: p.x, andY: p.y, withWidth: w, andHeight: h)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Our <code>right<\/code> property has been defined as a <code>Double<\/code> but notice that it doesn&#8217;t directly store a value. Instead, its getter uses the structure&#8217;s <code>left<\/code> and <code>width<\/code> properties to calculate and return the value of <code>right<\/code>.<\/p>\n<p>Our setter takes a value for our <code>right<\/code> computed property, but doesn&#8217;t actually store that value. Instead it uses it, along with the <code>left<\/code> stored property, to calculate and set a value for the rectangle&#8217;s <code>width<\/code> property.<\/p>\n<p>There&#8217;s a slight modification we can make to our setter. If you omit the parameter from the setter&#8217;s definition then Swift will provide a default parameter name of <code>newValue<\/code>. We can therefore change our setter from:<\/p>\n<p><codeswift>set(newRight) {<br \/>\n&nbsp;&nbsp;width = newRight &#8211; left<br \/>\n}<\/codeswift><\/p>\n<p>to:<\/p>\n<p><codeswift>set {<br \/>\n&nbsp;&nbsp;width = <codeswiftbold>newValue<\/codeswiftbold> &#8211; left<br \/>\n}<\/codeswift><\/p>\n<p>Let&#8217;s now go ahead and define a <code>bottom<\/code> computed property. We&#8217;ll also use the shorthand setter declaration just discussed:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top: Double<br \/>\n&nbsp;&nbsp;var width, height: Double<br \/>\n&nbsp;&nbsp;var right: Double {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return left + width<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;set {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width = newValue &#8211; left<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;<codeswiftbold>var bottom: Double {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return top + height<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;set {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;height = newValue &#8211; top<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;init(atX x: Double, andY y: Double, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;init(atPoint p: Point, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.init(atX: p.x, andY: p.y, withWidth: w, andHeight: h)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Now let&#8217;s create an instance of a <code>Rect<\/code> and make use of our <code>right<\/code> and <code>bottom<\/code> computed properties:<\/p>\n<p><codeswift>var target = Rect(atPoint: Point(x: 10, y: 50), withWidth: 200, andHeight: 50)<br \/>\nprintln(&quot;The rectangle has a width of: \\(target.width) and a height of: \\(target.height)&quot;)<br \/>\nprintln(&quot;Its bottom-right corner is at (\\(target.right), \\(target.bottom))&quot;)<\/codeswift><\/p>\n<p>This will output the following:<\/p>\n<p><codeswift>The rectangle has a width of: 200.0 and a height of: 50.0<br \/>\nIts bottom-right corner is at (210.0, 100.0)<\/codeswift><\/p>\n<p>Now change the width and height of your instance and once again query your properties. Enter the following into your playground:<\/p>\n<p><codeswift>target.width = 180<br \/>\ntarget.height = 100<br \/>\nprintln(&quot;The rectangle has a width of: \\(target.width) and a height of: \\(target.height)&quot;)<br \/>\nprintln(&quot;Its bottom-right corner is at (\\(target.right), \\(target.bottom))&quot;)<\/codeswift><\/p>\n<p>The following will now be output:<\/p>\n<p><codeswift>The rectangle has a width of: 180.0 and a height of: 100.0<br \/>\nIts bottom-right corner is at (190.0, 150.0)<\/codeswift><\/p>\n<p>Finally, set the <code>right<\/code> and <code>bottom<\/code> computed properties:<\/p>\n<p><codeswift>target.right = 220<br \/>\ntarget.bottom = 75<br \/>\nprintln(&quot;The rectangle has a width of: \\(target.width) and a height of: \\(target.height)&quot;)<br \/>\nprintln(&quot;Its bottom-right corner is at (\\(target.right), \\(target.bottom))&quot;)<\/codeswift><\/p>\n<p>The following should now be output:<\/p>\n<p><codeswift>The rectangle has a width of: 210.0 and a height of: 25.0<br \/>\nIts bottom-right corner is at (220.0, 75.0)<\/codeswift><\/p>\n<h3>Read-Only Computed Properties<\/h3>\n<p>It&#8217;s also possible to define a <strong><em>read-only computed property<\/em><\/strong>, which has a getter but no setter. Here&#8217;s one that returns the area of our rectangle:<\/p>\n<p><codeswift>var area: Double {<br \/>\n&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return width * height<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Alternatively, a shorthand version of a read-only computed property can be declared by removing the <code>get<\/code> keyword and its braces:<\/p>\n<p><codeswift>var area: Double {<br \/>\n&nbsp;&nbsp;return width * height<br \/>\n}<\/codeswift><\/p>\n<h3>Property Observers<\/h3>\n<p>Swift provides property observers, which let you observe and respond to changes in a stored property&#8217;s value. You can define one or both of the following observers on a property: <code>willSet<\/code> and <code>didSet<\/code>.<\/p>\n<p>The <code>willSet<\/code> observer is called just before a property&#8217;s value is changed, while <code>didSet<\/code> is called immediately after a property&#8217;s value has been modified.<\/p>\n<p>Here&#8217;s a simple example where we define observers for our <code>Rect<\/code> structure&#8217;s <code>width<\/code> property:<\/p>\n<p><codeswift>var width: Double {<br \/>\n&nbsp;&nbsp;willSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Setting width from: \\(width) to: \\(newValue)&quot;)<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Width changed from: \\(oldValue) to: \\(width)&quot;)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>We&#8217;ve used shorthand declarations for both of our above observers. The <code>willSet<\/code> observer exposes a default parameter named <code>newValue<\/code>, which contains the value that the property is about to be set to. The <code>didSet<\/code> observer exposes a default parameter named <code>oldValue<\/code>, which contains the property&#8217;s previous value before it was set.<\/p>\n<p>If you&#8217;d rather not use shorthand declarations for your observers then you can specify a parameter with each observer instead:<\/p>\n<p><codeswift>var width: Double {<br \/>\n&nbsp;&nbsp;willSet<codeswiftbold>(newWidth)<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Setting width from: \\(width) to: \\(<codeswiftbold>newWidth<\/codeswiftbold>)&quot;)<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;didSet<codeswiftbold>(oldWidth)<\/codeswiftbold> {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Width changed from: \\(<codeswiftbold>oldWidth<\/codeswiftbold>) to \\(width)&quot;)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Notice that there&#8217;s no need to explicitly specify the type of each observer&#8217;s parameter as the type is inferred from the property that is being observed.<\/p>\n<p>Before moving on, let&#8217;s look at a practical use for property observers. We&#8217;ll define a <code>didSet<\/code> observer for our rectangle&#8217;s <code>width<\/code> property that prevents it from being set to a negative value:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;var left, top: Double<br \/>\n&nbsp;&nbsp;var width :Double <codeswiftbold>{<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;didSet {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if width < 0 {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width = 0\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;right = left + width\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;}<\/codeswiftbold><br \/>\n&nbsp;&nbsp;var height: Double<br \/>\n&nbsp;&nbsp;var right :Double {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return left + width<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;set {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width = newValue &#8211; left<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;var bottom :Double {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;get {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return top + height<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;set {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;height = newValue &#8211; top<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;init(atX x: Double, andY y: Double, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<br \/>\n&nbsp;&nbsp;init(atPoint p: Point, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;self.init(atX: p.x, andY: p.y, withWidth: w, andHeight: h)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> We have a <code>didSet<\/code> observer for our structure&#8217;s <code>width<\/code> property now go ahead and add one for its <code>height<\/code> property. As with the <code>width<\/code> property, ensure that the rectangle&#8217;s height cannot be set to a negative value. Verify your code works by setting an instance&#8217;s height to a negative value then reading the current value back. <\/div><\/div>\n<h3>Type Properties<\/h3>\n<p>While a stored property belongs to an instance of a struct, a <strong><em>type property<\/em><\/strong> belongs to the struct itself. It&#8217;s important to note that there will only ever be one copy of a type property, no matter how many instances of that type are created.<\/p>\n<div class=\"zilla-alert white\"> Type properties are commonly known as static member variables in other languages such ActionScript and C++. <\/div>\n<p>A type property is defined with the <code>static<\/code> keyword and must also be given a default value when defined. Here&#8217;s an example of a type property that keeps track of the number of <code>Rect<\/code> instances that have been created:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;<codeswiftbold>static var instanceCount = 0<\/codeswiftbold><br \/>\n&nbsp;&nbsp;var top, left: Double<br \/>\n&nbsp;&nbsp;:<br \/>\n}<\/codeswift><\/p>\n<p>We can then increment it during every instance initialization:<\/p>\n<p><codeswift>struct Rect {<br \/>\n&nbsp;&nbsp;static var instanceCount = 0<br \/>\n&nbsp;&nbsp;var top, left :Double<br \/>\n&nbsp;&nbsp;:<br \/>\n&nbsp;&nbsp;init(atX x: Double, andY y: Double, withWidth w: Double, andHeight h: Double) {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;<codeswiftbold>Rect.instanceCount++<\/codeswiftbold><br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;left = x<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;top = y<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;width = w<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;height = h<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>Dot syntax is used to get and set the value of type properties. However, unlike instances, type properties are queried and set on the type, rather than the instance itself. Here&#8217;s the line from our initailizer where our type property is incremented:<\/p>\n<p><codeswift>Rect.instanceCount++<\/codeswift><\/p>\n<p>We can just as easily obtain the type property&#8217;s value:<\/p>\n<p><codeswift>println(&quot;\\(Rect.instanceCount) instances of Rect have been created.&quot;)<\/codeswift><\/p>\n<h3>Structs as Constants<\/h3>\n<p>Our <code>Rect<\/code> and <code>Point<\/code> examples have used variable stored properties. However, creating a constant instance of any of these structures will prevent you from being able to change the instance&#8217;s properties, even though those properties have been defined as variables.<\/p>\n<p>Take the following for example:<\/p>\n<p><codeswift>let origin = Point()<br \/>\norigin.x = 100<\/codeswift><\/p>\n<p>Attempting to change the value of the instance&#8217;s <code>x<\/code> property will result in the following compile-time error: <code>Cannot assign to 'x' in 'origin'<\/code>.<\/p>\n<h3>Methods<\/h3>\n<p>Unlike languages such as C and Objective-C, Swift lets you define methods on a structure. In fact, you can even define a method on an enumeration too.<\/p>\n<p>Since methods are more commonly associated with classes, and to give you time to digest what&#8217;s been covered so far, we&#8217;ll hold off and cover them in the next tutorial.<\/p>\n<h2>Next Time<\/h2>\n<p>We&#8217;ve seen just how flexible functions in Swift can be. ActionScript and TypeScript developers will find that the form of a basic Swift function isn&#8217;t a million miles away from what they&#8217;re used to. iOS developers on the other hand will no-doubt be delighted to find that complex Objective-C style functions with local and external parameter names for each parameter can also be constructed.<\/p>\n<p>The second half of this tutorial was spent covering structures, which along with functions, are used as building blocks for any programs you write. Covering both functions and structures here was important as they both naturally lead onto the concept of classes, which we&#8217;ll cover in part four.<\/p>\n<p>See you soon.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to the third tutorial in the series. Here we will cover functions and structures. This will put us in good stead for part four where we&#8217;ll finally get onto the subject of object-oriented programming. What you will learn&#8230; How to define and call functions How to work with structures What you should know&#8230; The [&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-999","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"_links":{"self":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/999","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=999"}],"version-history":[{"count":39,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/999\/revisions"}],"predecessor-version":[{"id":1056,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/999\/revisions\/1056"}],"wp:attachment":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=999"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=999"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=999"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}