{"id":522,"date":"2014-09-11T09:44:50","date_gmt":"2014-09-11T09:44:50","guid":{"rendered":"http:\/\/www.yeahbutisitswift.com\/?p=522"},"modified":"2015-05-12T20:06:30","modified_gmt":"2015-05-12T20:06:30","slug":"quick-start-guide-to-swift-part-1-2","status":"publish","type":"post","link":"http:\/\/www.yeahbutisitswift.com\/?p=522","title":{"rendered":"Quick Start Guide to Swift: Part 1"},"content":{"rendered":"<p>Dive into the Swift programming language with this quick start guide that will have you up and running in no time.<\/p>\n<h3>What you will learn&#8230;<\/h3>\n<ul>\n<li>How to work with playgrounds<\/li>\n<li>The basics of the Swift programming language<\/li>\n<li>Grouping multiple values into a tuple<\/li>\n<li>How to work with optionals<\/li>\n<li>String fundamentals<\/li>\n<li>Control flow<\/li>\n<\/ul>\n<h3>What you should know&#8230;<\/h3>\n<ul>\n<li>A familiarity with at least one programming language<\/li>\n<\/ul>\n<p>Swift is Apple&#8217;s innovative new programming language. If you&#8217;ve always wanted to develop iOS or OS X apps but were put off by the seeming complexity of Objective-C then this might be the perfect time to give it a try.<\/p>\n<p>Swift is modern and has been designed to be friendly to new programmers. It&#8217;s expressive and is as enjoyable to use as a scripting language. In fact, if you&#8217;re coming from a JavaScript or ActionScript background then large parts of Swift will actually feel familiar to you.<\/p>\n<p>This tutorial series however isn&#8217;t just for ECMAScript programmers. Those already familiar with Objective-C, or from a Java or C background, will also find this a good resource for transitioning over to Swift.<\/p>\n<p>Everything covered in this series of tutorials can also be found in Apple&#8217;s own official guide to the Swift programming language. The intention here however is to focus on the elements of the language that are required to get newcomers up and running as quickly as possible. If you have the time and want the full detail then I highly recommend you head straight over to Apple&#8217;s <a href=\"https:\/\/developer.apple.com\/library\/prerelease\/ios\/documentation\/Swift\/Conceptual\/Swift_Programming_Language\" target=\"_blank\">Swift Programming Language Guide<\/a> instead.<\/p>\n<p><!--more--><\/p>\n<h2>Getting Started<\/h2>\n<p>Let&#8217;s start by installing Xcode 6. You can download it from the <a href=\"https:\/\/developer.apple.com\/swift\/resources\/\" target=\"_blank\">Swift Resources<\/a> page. Of course, you&#8217;ll need a Mac and OS X to run Xcode, but if you&#8217;re on a different platform then you can still read through this tutorial and learn a lot about the language.<\/p>\n<p>Once installed, launch Xcode 6. You&#8217;ll be greeted by Xcode&#8217;s Welcome window. From here you can immediately start experimenting with Swift by opening a new <em><strong>playground<\/strong><\/em> file. But what is a playground?<\/p>\n<p>Playgrounds make writing Swift code easy and fun. When working from a playground file you can type lines of code and see the result immediately. There is no need to create and build an Xcode project. Playgrounds is a perfect interactive environment for learning Swift and trying out new ideas. For that very reason we&#8217;ll use it during this tutorial series.<\/p>\n<p>Okay, let&#8217;s create a playground to work from.<\/p>\n<div id=\"attachment_516\" style=\"width: 510px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-516\" src=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-1024x600.png\" alt=\"Figure 1. Getting started with a playground.\" width=\"500\" height=\"292\" class=\"size-large wp-image-516\" srcset=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-1024x600.png 1024w, http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-300x175.png 300w, http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-750x439.png 750w, http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-450x263.png 450w, http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode-280x164.png 280w, http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/welcome-to-xcode.png 1254w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/a><p id=\"caption-attachment-516\" class=\"wp-caption-text\">Figure 1. Getting started with a playground.<\/p><\/div>\n<p>Do that by selecting the <strong>Get started with a playground<\/strong> option from Xcode&#8217;s Welcome window. A new window will appear where you can set the name for your playground file and your target platform. Ensure the target platform is set to <strong><code>iOS<\/code><\/strong> and name your file <strong><code>Quick Start Guide Part 1<\/code><\/strong>. Click <strong>Next<\/strong> then select a suitable location on your hard drive to save the playground file to. Finally, click <strong>Create<\/strong>.<\/p>\n<div id=\"attachment_455\" style=\"width: 510px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/choose-options-for-your-new-file.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-455\" src=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/choose-options-for-your-new-file-1024x767.png\" alt=\"Figure 2. Naming your playground file.\" width=\"500\" height=\"389\" class=\"size-large wp-image-455\" \/><\/a><p id=\"caption-attachment-455\" class=\"wp-caption-text\">Figure 2. Naming your playground file.<\/p><\/div>\n<p>Congratulations! You&#8217;ve just created your first ever playground file and are now ready to start experimenting with the Swift programming language. You&#8217;ll be presented with a window that&#8217;s split into two columns.<\/p>\n<div id=\"attachment_473\" style=\"width: 510px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/playground-window.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-473\" src=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/playground-window-1024x767.png\" alt=\"Figure 3. Your playground window.\" width=\"500\" height=\"389\" class=\"size-large wp-image-473\" \/><\/a><p id=\"caption-attachment-473\" class=\"wp-caption-text\">Figure 3. Your playground window.<\/p><\/div>\n<p>On the left-hand side is where you&#8217;ll enter your Swift code. In fact, you should see some default code already sitting there. On the right is a sidebar where the results of your evaluated code will be shown.<\/p>\n<p>Your playground window also provides a timeline assistant, which comes in handy when working with code that runs over time. For example, if you write a loop, you can watch its progress in graph form, with the value of each of the loop&#8217;s variables clearly charted over time. However, focusing on the sidebar for the time being will be more than enough to get us up and running.<\/p>\n<p>Feel free to delete the code that&#8217;s already within your playground. Now let&#8217;s get the ball rolling.<\/p>\n<h2>Your First Program<\/h2>\n<p>Take a look at the following line:<\/p>\n<p><codeswift>println(&#8220;Hullo World!&#8221;)<\/codeswift><\/p>\n<p>If you were to save the above within a text file and give it the <code>.swift<\/code> extension, you&#8217;d have written the simplest program you can write with the Swift programming language.<\/p>\n<p>That&#8217;s right, just a single line of text and you have a working program. Any code written at the global scope is used as your program&#8217;s main entry point, and there&#8217;s no need to import a library to handle output of your string either.<\/p>\n<p>You may also notice one curious omission. There&#8217;s no semicolon at the end of the line. Semicolons aren&#8217;t required at the end of every statement. Adding semicolons to the end of a statement is a hard habit to break. Hang on in there though and you&#8217;ll soon learn to live without them.<\/p>\n<p>Try the above example out by typing it into your playground window. Hitting the <em>Enter<\/em> key will result in <code>Hullo World!<\/code> being displayed within the sidebar.<\/p>\n<div class=\"zilla-alert white\"> If we were running our code from an Xcode project rather than a playground, then <code>Hullo World!<\/code> would have been displayed within Xcode&#8217;s console panel rather than your playground&#8217;s sidebar.<\/p>\n<p>There are various destinations that text can be written to depending on the context in which you are running Swift. It&#8217;s therefore better to refer to those destinations collectively as <em><strong>the appropriate output<\/strong><\/em>. We&#8217;ll use that term throughout. <\/div>\n<h2>Comments<\/h2>\n<p>Comments in Swift are similar to comments in most languages. Here&#8217;s an example of a single-line comment:<\/p>\n<p><codeswift>\/\/ Player has been killed.<\/codeswift><\/p>\n<p>Comments can also span several lines:<\/p>\n<p><codeswift>\/* The player has collided with a projectile. Reduce their energy and<br \/>\n&nbsp;&nbsp;&nbsp;check to see if the collision killed them. *\/<\/codeswift><\/p>\n<p>Unlike most languages, multiline comments can also be nested inside other multiline comments. This is particularly useful if you need to quickly comment out large blocks of code that already contain multiline comments.<\/p>\n<h2>Variables and Constants<\/h2>\n<p>Variables are declared with the <code>var<\/code> keyword. Here&#8217;s an example of a variable that stores the number of lives a player has:<\/p>\n<p><codeswift>var remainingLives = 2<\/codeswift><\/p>\n<p>Constants can also be declared. Use the <code>let<\/code> keyword:<\/p>\n<p><codeswift>let maximumLives = 5<\/codeswift><\/p>\n<p>You can also declare multiple variables or multiple constants on a single line:<\/p>\n<p><codeswift>var remainingLives = 3, score = 0, level = 0<\/codeswift> <\/p>\n<p>Use constants for any values that will not change during the lifetime of your program.<\/p>\n<p>When you declare a constant you must also provide it with an initial value. Unlike a constant, a variable does not require an initial value when being declared. However, a value must be assigned before the variable is actually used.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> In your playground, declare and initialise a constant named <code>maximumLevel<\/code> on one line then attempt to change its value on the next:<\/p>\n<p><codeswift>let maximumLevel = 20<br \/>\nmaximumLevel = 25<\/codeswift><\/p>\n<p>You&#8217;ll receive the following error:<\/p>\n<p><codeswift>Cannot assign to &#8216;let&#8217; value &#8216;maximumLevel&#8217;<\/codeswift><br \/>\n <\/div><\/div>\n<h2>Types and Type Inference<\/h2>\n<p>You probably noticed that a type was not specified for any of the variables or constants. Swift can infer the type you intend to use from the initial value you provide. The following declares a constant that stores a string:<\/p>\n<p><codeswift>let name = &#8220;Luke Skywalker&#8221;<\/codeswift><\/p>\n<p>When you need to be clear about the type being used you can specify it by placing a colon after the constant or variable name:<\/p>\n<p><codeswift>let name: String = &#8220;Luke Skywalker&#8221;<\/codeswift> <\/p>\n<p>In most situations however, you shouldn&#8217;t need to explicitly state the type you intend to use.<\/p>\n<p>Swift provides types for integers, floating-point numbers, strings, characters and boolean values.<\/p>\n<h3>Integers<\/h3>\n<p>Integers are represented by signed and unsigned types in 8 (<code>Int8<\/code>, <code>UInt8<\/code>), 16 (<code>Int16<\/code>, <code>UInt16<\/code>), 32 (<code>Int32<\/code>, <code>UInt32<\/code>), and 64 (<code>Int64<\/code>, <code>UInt64<\/code>) bit forms. However, you really don&#8217;t need to worry about the specific size of an integer. Instead, use the <code>Int<\/code> integer type, which is represented by <code>Int32<\/code> on a 32-bit platform, and <code>Int64<\/code> on a 64-bit platform. Here is an example:<\/p>\n<p><codeswift>var age: Int = 16<\/codeswift><\/p>\n<p>Alternatively, as discussed earlier, the type can be inferred:<\/p>\n<p><codeswift>var age = 16<\/codeswift><\/p>\n<p>An unsigned integer type, <code>UInt<\/code>, is also available:<\/p>\n<p><codeswift>var age: UInt = 16<\/codeswift><\/p>\n<p>However, it&#8217;s recommended that you use <code>Int<\/code> even for values that are known only to be non-negative. This avoids the need to convert between different number types.<\/p>\n<h3>Floating-Point Numbers<\/h3>\n<p>If you need to store a number with a fractional component or a much larger number than can be stored with an integer type, then use either the <code>Float<\/code> or <code>Double<\/code> type. A <code>Double<\/code> has a precision of at least 15 digits whereas a <code>Float<\/code> can have a precision of at least 6 decimal digits:<\/p>\n<p><codeswift>let value1: Float = 1 \/ 3<br \/>\nlet value2: Double = 1 \/ 3<\/codeswift><\/p>\n<p>Of course, you can stop worrying about the exact type and let Swift make that decision for you:<\/p>\n<p><codeswift>let value3 = 1.0 \/ 3<\/codeswift><\/p>\n<p>Use <code>Double<\/code> only when you require the additional precision or to store a number that&#8217;s too large to be represented by <code>Float<\/code>.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">In the example directly above, notice that the value 1 is written as a floating-point value (<code>1.0<\/code>). This is to ensure that the <code>value3<\/code> constant is implicitly declared of type <code>Double<\/code>. If two integers had been divided instead, Swift would have incorrectly inferred that an integer type was to be used for your <code>value3<\/code> constant, which would have resulted in it being initialised with a value of <code>0<\/code>.<\/p>\n<p>You can test this directly within your playground. Go ahead and enter the following:<\/p>\n<p><codeswift>let value1: Float = 1 \/ 3<br \/>\nlet value2 = 1.0 \/ 3<br \/>\nlet value3 = 1 \/ 3<\/codeswift><\/p>\n<p>If you examine the sidebar you&#8217;ll notice that <code>value3<\/code> contains a value of <i>0<\/i>, which is probably not what you expected.<\/p>\n<p>This is a common mistake made by those coming from languages such as JavaScript.<\/div><\/div>\n<h3>Boolean<\/h3>\n<p>Swift has a <code>Bool<\/code> type and provides two constant values, <code>true<\/code> and <code>false<\/code> for you to work with. Here are some examples:<\/p>\n<p><codeswift>var shieldActivated = false<br \/>\nvar isAlive = true<br \/>\nlet catsHateDogs = true<\/codeswift><\/p>\n<p>Of course, with all three variables above, you could have declared each as being of type <code>Bool<\/code>. However the use of the <code>Bool<\/code> type is inferred by assigning either <code>true<\/code> or <code>false<\/code> to each.<\/p>\n<h3>Strings<\/h3>\n<p>Swift represents strings with the <code>String<\/code> type, which is essentially a collection of characters:<\/p>\n<p><codeswift>let jedi = &#8220;Luke Skywalker&#8221;<br \/>\nlet sith = &#8220;Darth Vader&#8221;<\/codeswift><\/p>\n<p>As expected, in the example above, the <code>String<\/code> type is inferred by the fact that a string literal is used to initialise each constant.<\/p>\n<p>It&#8217;s worth noting that a Swift string is a value type. In other words, the value of the string is copied when passed to a function or method. The same is also true when a string is assigned to another constant or variable. This is different to the behaviour of Objective-C where a reference to a string is used instead.<\/p>\n<p>Strings can be concatenated to create a new string:<\/p>\n<p><codeswift>var forename = &#8220;Christopher&#8221;<br \/>\nvar surname = &#8220;Caleb&#8221;<br \/>\nlet fullName = forename + &#8221; &#8221; + surname<\/codeswift><\/p>\n<p>Strings that are represented by constants cannot be modified once they are initialised.<\/p>\n<h3>Printing Values<\/h3>\n<p>As you have already seen, you can print a string to the appropriate output (Xcode&#8217;s console pane for example) using the global <code>println<\/code> function:<\/p>\n<p><codeswift>println(&#8220;May the force be with you.&#8221;)<\/codeswift><\/p>\n<p>You can also print the current value of any variable or constant:<\/p>\n<p><codeswift>var name = &#8220;Obi-Wan Kenobi&#8221;<br \/>\nprintln(name)<\/codeswift><\/p>\n<p>It&#8217;s also possible to insert variables or constants as placeholders directly within a string. This is done by wrapping the name in parentheses and escaping it with a backslash before the opening parenthesis:<\/p>\n<p><codeswift>var player1 = &#8220;Vader&#8221;<br \/>\nvar player2 = &#8220;Yoda&#8221;<br \/>\nprintln(&#8220;\\(player1) vs. \\(player2)&#8221;)<\/codeswift><\/p>\n<p>The example above will print <code>Vader vs. Yoda<\/code> to the appropriate output.<\/p>\n<h3>Type Conversion<\/h3>\n<p>Each number type has a different range. For example, the <code>Int8<\/code> type can store any value ranging from <code>-128<\/code> to <code>127<\/code>. The <code>UInt8<\/code> type has a range from <code>0<\/code> to <code>255<\/code>. A variable or constant whose value is too small or too large for its specified type will result in a compile-time error. For example, this will result in an error:<\/p>\n<p><codeswift>let tooBig: Int8 = Int8.max + 1<\/codeswift><\/p>\n<p>In other words, Swift does not attempt to automatically handle numeric overflow. By refusing to do so it prevents hidden conversion errors. Instead, if you are dealing with different numeric types then you must explicitly convert all your values to the same type. Take a look at the following:<\/p>\n<p><codeswift>let numberOfKills: UInt16 = 2400<br \/>\nlet remainingTime: UInt8 = 12<br \/>\nlet finalScore = numberOfKills * UInt16(remainingTime)<\/codeswift><\/p>\n<p>In the example above, the value of the <code>finalScore<\/code> constant is calculated by multiplying the value of <code>numberOfKills<\/code> with <code>remainingTime<\/code>. However, since <code>numberOfKills<\/code> and <code>remainingTime<\/code> are both of different types, one of the types must first be converted to match that of the other. In our example, this is done by calling <code>UInt16(remainingTime)<\/code> to convert the <code>remainingTime<\/code> constant to the same type as <code>numberOfKills<\/code>.<\/p>\n<p><code>UInt16(remainingTime)<\/code> is an example of a type&#8217;s initializer being called and passed an initial value. This is known as initializer syntax and can be used to initialise a variable or constant of any numeric type. Here&#8217;s a similar example, but this time, both constants are converted to <code>Int8<\/code> types before the final score is calculated:<\/p>\n<p><codeswift>let numberOfKills: UInt8 = 10<br \/>\nlet bonusPoints: Int8 = -2<br \/>\nlet finalScore = Int8(numberOfKills) + bonusPoints<\/codeswift><\/p>\n<p>Conversion between floating point and integer number types must also be handled explicitly. Here&#8217;s an example, where the <code>numberOfKills<\/code> variable is converted from an <code>Int<\/code> to a <code>Double<\/code>:<\/p>\n<p><codeswift>var numberOfKills = 21<br \/>\nvar remainingSeconds = 2.45<br \/>\nlet finalScore = Double(numberOfKills) * remainingSeconds<\/codeswift> <\/p>\n<p>It&#8217;s also possible to convert a floating-point value to an integer, although there will be a loss of precision:<\/p>\n<p><codeswift>let remainingSeconds = 2.45<br \/>\nlet pi = 3.14<br \/>\nlet height = 5.9<br \/>\nlet temperature = -3.9<br \/>\nprintln(&#8220;remaining seconds: \\(Int(remainingSeconds))&#8221;)<br \/>\nprintln(&#8220;pi: \\(Int(pi))&#8221;)<br \/>\nprintln(&#8220;height: \\(Int(height))&#8221;)<br \/>\nprintln(&#8220;temperature: \\(Int(temperature))&#8221;)<\/codeswift><\/p>\n<p>When run, the following will be appear in the appropriate output:<\/p>\n<p><codeswift>remaining seconds: 2<br \/>\npi: 3<br \/>\nheight: 5<br \/>\ntemperature: -3<\/codeswift><\/p>\n<p>A conversion from floating-point to integer is always truncated. For example, <code>5.9<\/code> will become <code>5<\/code>, whereas <code>-3.9<\/code> will be converted to <code>-3<\/code>.<\/p>\n<h3>Tuples<\/h3>\n<p>You can group multiple values into a single compound value through the use of a tuple. The values stored within a tuple do not have to be of the same type. The following example groups information about the non-Retina iPad&#8217;s screen resolution:<\/p>\n<p><codeswift>let iPadStandard = (768, 1024, &#8220;standard&#8221;)<\/codeswift><\/p>\n<p>Remember, Swift infers the type of each value. However if you did want to be explicit:<\/p>\n<p><codeswift>let iPadStandard: (Int, Int, String) = (768, 1024, &#8220;standard&#8221;)<\/codeswift><\/p>\n<p>You can access an individual value within a tuple by specifying that value&#8217;s position. The following example obtains the screen resolution&#8217;s width and height:<\/p>\n<p><codeswift>var width = iPadStandard.0<br \/>\nvar height = iPadStandard.1<br \/>\nprintln(&#8220;The screen is \\(width) pixels wide and \\(height) pixels high.&#8221;)<\/codeswift><\/p>\n<p>Rather than working with index positions you can also decompose a tuple like this:<\/p>\n<p><codeswift>var (width, height, screenType) = iPadStandard<br \/>\nprintln(&#8220;The screen is \\(width) pixels wide and \\(height) pixels high.&#8221;)<\/codeswift><\/p>\n<p>The example above creates three variables (<code>width<\/code>, <code>height<\/code>, and <code>screenType<\/code>) and assigns each of them to a value within the tuple.<\/p>\n<p>Notice that we had no need for the <code>screenType<\/code> variable in our example. You can use an underscore to ignore values you don&#8217;t require when decomposing a tuple:<\/p>\n<p><codeswift>var (width, height, _) = iPadStandard<br \/>\nprintln(&#8220;The screen is \\(width) pixels wide and \\(height) pixels high.&#8221;)<\/codeswift><\/p>\n<p>You can also assign a name to individual elements within a tuple. Here&#8217;s our non-Retina iPad example again but with a name associated with each element:<\/p>\n<p><codeswift>let iPadStandard = (width: 768, height: 1024, screenType: &#8220;standard&#8221;)<br \/>\nvar width = iPadStandard.width<br \/>\nvar height = iPadStandard.height<br \/>\nprintln(&#8220;The screen is \\(width) pixels wide and \\(height) pixels high.&#8221;)<\/codeswift><\/p>\n<p>Tuples are ideal for temporarily storing groups of related data. They are also an extremely powerful means of returning multiple values from a function or method. They aren&#8217;t however, suitable for representing complex data structures. <\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">We&#8217;ve already created a tuple to store details regarding a non-Retina iPad. Try adding three new constants that represent the Retina iPad, non-Retina iPhone, and the Retina iPhone 4.<\/p>\n<p>Now create a variable named <code>currentScreen<\/code> and arbitrarily assign it to the various constants. Using that variable, extract values from each and print them using the <code>printlin()<\/code> function.<\/div><\/div>\n<h3>Optionals<\/h3>\n<p>It was stated earlier that a variable or constant must be assigned a value before it can be used. How do we handle variables that, for one reason or another, may not hold a value at various points during your program&#8217;s execution? Swift provides <code>nil<\/code>, which is a special value that represents a valueless state.<\/p>\n<p>You therefore might reasonably expect to see code like this in Swift:<\/p>\n<p><codeswift>var middleName: String = nil<\/codeswift><\/p>\n<p>After all, not everyone has a middle name. Unfortunately Swift variables cannot be <code>nil<\/code>. They must always have a value associated with them.<\/p>\n<p>In such situations you would use an <strong><i>optional<\/i><\/strong> variable instead. By using an optional you are saying that the variable will either have a value, or no value at all. An optional type has a question mark placed after it. Here&#8217;s our middle name example again, but this time using an optional:<\/p>\n<p><codeswift>var middleName: String?<\/codeswift><\/p>\n<p>Notice that, in this case, the optional string type has to be explicitly stated. It&#8217;s also defaulted to <code>nil<\/code>.<\/p>\n<p>Let&#8217;s set our <code>middleName<\/code> variable to something:<\/p>\n<p><codeswift>middleName = &#8220;Tiberius&#8221;<\/codeswift><\/p>\n<h4>Forced Unwrapping<\/h4>\n<p>Now that we have a value stored within our optional, we can consider using it. To retrieve a value from an optional you have to <strong><i>unwrap<\/i><\/strong> it by placing an exclamation mark at the end of the optional&#8217;s name:<\/p>\n<p><codeswift>println(&#8220;James \\(middleName!) Kirk&#8221;)<\/codeswift><\/p>\n<p>Before you can unwrap an optional though, you must first check that it contains a value. In other words, you must check that your optional is not <code>nil<\/code>.<\/p>\n<p><codeswift>if middleName != nil {<br \/>\n&nbsp;&nbsp;println(&#8220;James \\(middleName!) Kirk&#8221;)<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> We used an <code>if<\/code> statement in the example above but haven&#8217;t yet covered control flow yet. It should be fairly obvious how it works though. <\/div>\n<p>By using the exclamation mark to obtain the optional&#8217;s value, you are stating that you are absolutely sure that the optional does actually contain a non-<code>nil<\/code> value. This is known as <strong><i>forced unwrapping<\/i><\/strong>, and doing so on a variable that contains <code>nil<\/code> will result in a runtime error.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">You&#8217;ll be using optionals a lot in Swift so try to get comfortable using them.<\/p>\n<p>Create a few optional constants. Each optional should be initialised to a string literal that contains the name of a friend. Print each of your friend names (one <code>println()<\/code> for each friend) and check the result in the sidebar. Verify that you&#8217;ve actually unwrapped your optional by checking that the keyword <code>Optional<\/code> doesn&#8217;t appear in the sidebar next to each of your <code>println()<\/code> statements.<\/p>\n<p>Now go back and initialise each of your constants to <code>nil<\/code>. Ensure that nothing is now being printed to the sidebar and confirm that you aren&#8217;t receiving any runtime errors.<br \/>\n <\/div><\/div>\n<h4>Optional Binding<\/h4>\n<p>As an alternative to using an <code>if<\/code> statement before obtaining an optional&#8217;s value, you can also use a technique known as <strong><i>optional binding<\/i><\/strong>. It works by checking that an optional contains a value and then storing that value in a temporary variable or constant for you to work with. Here&#8217;s our middle name example again, but this time taking advantage of optional binding:<\/p>\n<p><codeswift>var middleName: String?<br \/>\nmiddleName = &#8220;Tiberius&#8221;<br \/>\nif let name = middleName {<br \/>\n&nbsp;&nbsp;println(&#8220;James \\(name) Kirk&#8221;)<br \/>\n}<\/codeswift><\/p>\n<p>The example above checks to see if the <code>middleName<\/code> optional contains a value. If it does then it sets a new constant called <code>name<\/code> to the value contained within <code>middleName<\/code>. That constant is then made available within the first branch of the <code>if<\/code> statement.<\/p>\n<p>Also, since the <code>name<\/code> constant has already been initialised with the value stored within the optional, there is no need to forcibly unwrap it with an exclamation mark. The <code>name<\/code> constant is a string rather than an optional. In other words, the <code>name<\/code> constant is a <strong>non-optional<\/strong> type.<\/p>\n<h4>Implicitly Unwrapped Optionals<\/h4>\n<p>Sometimes you&#8217;ll want to work with an optional that you know for sure will always have a value after it&#8217;s first set. For example, you may write a video game that loads the current highest score from the file system. Initially your variable will contain <code>nil<\/code> while the high score is being loaded, but once that high score is set, the structure of your game guarantees that your variable will always contain a score.<\/p>\n<p>In such cases, checking and unwrapping the optional every time you want to access its data is unnecessary. You can actually remove the need to do this by using an <strong><i>implicitly unwrapped optional<\/i><\/strong>.<\/p>\n<p>An implicitly unwrapped optional is created by placing an exclamation mark after its type rather than a question mark. Here&#8217;s an example:<\/p>\n<p><codeswift>var highScore: Int! = nil<\/codeswift><\/p>\n<p>Once the <code>highScore<\/code> variable has been set to a value you can then use it like any <strong>non-optional<\/strong> value:<\/p>\n<p><codeswift>highScore = 10000<br \/>\nprintln(&#8220;The high score is: \\(highScore) points&#8221;)<\/codeswift><\/p>\n<p>Notice that there was no need for an exclamation mark immediately after the <code>highScore<\/code> variable on either lines.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Revisit the previous playground experiment but this time use implicitly unwrapped optionals.<br \/>\n <\/div><\/div>\n<h2>Basic Operators<\/h2>\n<p>Swift&#8217;s basic operators will be familiar to most developers. It also provides support for a few special operators such as the <strong><i>nil coalescing<\/i><\/strong> operator and two <strong><i>range operators<\/i><\/strong>. We&#8217;ll cover the range operators shortly but will leave the nil coalescing operator for another day.<\/p>\n<h3>Assignment Operator<\/h3>\n<p>We&#8217;ve already seen the assignment operator (<code>=<\/code>) used to initialise variables and constants, and of course it can just as easily be used to assign the value of one variable to another.<\/p>\n<p>Unlike many languages, Swift&#8217;s assignment operator does not return a value. The following statement isn&#8217;t valid:<\/p>\n<p><codeswift>if energy = maxEnergy {<br \/>\n&nbsp;&nbsp;\/\/ Do something<br \/>\n}<\/codeswift><\/p>\n<p>This feature prevents the assignment operator from accidentally being used when the equal-to (<code>==<\/code>) operator was actually intended.<\/p>\n<h3>Arithmetic Operators<\/h3>\n<p>As you would expect, the standard arithmetic operators (<code>+<\/code>, <code>-<\/code>, <code>*<\/code>, and <code>\/<\/code>) are all supported by Swift.<\/p>\n<h3>Remainder Operator<\/h3>\n<p>Swift supports the modulo operator (<code>%<\/code>). Its implementation is slightly different to that found in most other languages and is therefore better described as the <i><strong>remainder operator<\/strong><\/i>. Here are some examples:<\/p>\n<p><codeswift>&nbsp;9 % 4 &nbsp;\/\/ equals 1<br \/>\n&nbsp;9 % -4 \/\/ equals 1<br \/>\n-9 % 4 &nbsp;\/\/ equals -1<br \/>\n-9 % -4 \/\/ equals -1<\/codeswift><\/p>\n<p>Unlike some other languages, Swift&#8217;s remainder operator can work with floating-point numbers:<\/p>\n<p><codeswift>11 % 3.5 \/\/ equals 0.5<br \/>\n10.5 % 6.4 \/\/ equals 4.1<\/codeswift><\/p>\n<h3>Increment and Decrement Operators<\/h3>\n<p>The increment (<code>++<\/code>) and decrement (<code>--<\/code>) operators behave as expected:<\/p>\n<p><codeswift>var a = 1<br \/>\nvar b = a++ \/\/ b equals 1<br \/>\nvar c = ++a \/\/ c equals 3<br \/>\nvar d = &#45;&#45;a &nbsp;\/\/ d equals 2<br \/>\nvar e = a&#45;&#45; &nbsp;\/\/ e equals 2<\/codeswift><\/p>\n<h3>Compound Assignment Operators<\/h3>\n<p>Compound assignment statements are also supported. Here are a few examples:<\/p>\n<p><codeswift>var a = 1<br \/>\na += 4 \/\/ a equals 5<br \/>\na -= 1 \/\/ a equals 4<br \/>\na *= 2 \/\/ a equals 8<br \/>\na \/= 4 \/\/ a equals 2<\/codeswift><\/p>\n<h3>Comparison Operators<\/h3>\n<p>Swift supports all the usual comparison operators found in most other languages: equal to (<code>a == b<\/code>), not equal to (<code>a != b<\/code>), greater than (<code>a > b<\/code>), less than (<code>a < b<\/code>), greater than or equal to (<code>a >= b<\/code>), and finally, less than or equal to (<code>a <= b<\/code>).<\/p>\n<h3>Logical Operators<\/h3>\n<p>Swift has support for the three standard logical operators: logical AND (<code>a & b<\/code>), logical OR (<code>a | b<\/code>), and logical NOT (<code>!a<\/code>).<\/p>\n<p>Of course, you can also combine multiple logical operators to create longer compound expressions.<\/p>\n<h3>Range Operators<\/h3>\n<p>Swift provides a <strong><i>closed range<\/i><\/strong> operator and a <strong><i>half-open range<\/i><\/strong> operator. These operators are useful when expressing a range of values.<\/p>\n<p>The closed range operator <code>(a...b)<\/code> defines a range from <code>a<\/code> to <code>b<\/code>, and includes both <code>a<\/code> and <code>b<\/code>. The closed range operator is useful when iterating over a range of values with a <code>for-in<\/code> loop. Here's an example:<\/p>\n<p><codeswift>for i in 0...5 {<br \/>\n&nbsp;&nbsp;println(i)<br \/>\n}<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> More on loops in the section directly below. <\/div>\n<p>The example above will print the following to the appropriate output:<\/p>\n<p><codeswift>0<br \/>\n1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<\/codeswift><\/p>\n<p>The half-open range operator <code>(a..&lt;b)<\/code> defines a range from <code>a<\/code> to <code>b<\/code>, but does not include <code>b<\/code>:<\/p>\n<p><codeswift>for i in 0..<5 {\n&nbsp;&nbsp;println(i)\n}<\/codeswift><\/p>\n<p>This will result in the following being sent to the appropriate output:<\/p>\n<p><codeswift>0<br \/>\n1<br \/>\n2<br \/>\n3<br \/>\n4<\/codeswift><\/p>\n<h2>For Loops<\/h2>\n<p>Swift provides a <code>for<\/code> loop and a <code>for-in<\/code> loop. Let's begin with the <code>for<\/code> loop.<\/p>\n<h3>For Loop<\/h3>\n<p>The general structure of a <code>for<\/code> loop should look familiar. Take a look at this code snippet:<\/p>\n<p><codeswift>for var index = 0; index < 5; ++index {\n&nbsp;&nbsp;println(\"index: \\(index)\")\n}<\/codeswift><\/p>\n<p>The only real difference between a <code>for<\/code> loop in Swift compared to most other languages is that parentheses aren't required. The example above will result in the following being printed to the appropriate output:<\/p>\n<p><codeswift>index: 0<br \/>\nindex: 1<br \/>\nindex: 2<br \/>\nindex: 3<br \/>\nindex: 4<\/codeswift> <\/p>\n<div class=\"zilla-alert white\"> In order to see the results of a loop within your playground you'll need to take advantage of the timeline assistant. To do this, look in the sidebar, directly along from your loop's <code>println()<\/code> call. You should see the text <code>(5 times)<\/code> and an icon of a dot to the right of that.<\/p>\n<div align=\"center\" style=\"margin-bottom:20px;\"><a href=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/timeline-assistant.png\"><img decoding=\"async\" style=\"width:440px;\" src=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/09\/timeline-assistant-1024x189.png\" alt=\"timeline-assistant\" \/><\/a><\/div>\n<p>If you click that icon, the timeline assistant pane will open and you'll be able to see the result from each iteration of your loop. <\/div>\n<p>Block scope is important. Variables and constants declared within a loop are only valid within the scope of the loop. This includes any variables and constants declared as part of the <code>for<\/code> loop's initialisation block. This often trips-up developers who have a background in ECMAScript-based languages such as JavaScript and ActionScript since these scripting languages don't support block scope.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Write a small program that calculates the sum of numbers between 1 and 100 inclusive. Print the result.<br \/>\n <\/div><\/div>\n<h3>For-In Loop<\/h3>\n<p>The <code>for-in<\/code> loop is used to iterate over collections of items. This can include such things as a range of numbers, items in an array, the contents of a dictionary, or the characters in a string.<\/p>\n<p>We'll look at a simple example here, then see more uses for the <code>for-in<\/code> loop in part two of this series:<\/p>\n<p><codeswift>for index in 0...4 {<br \/>\n&nbsp;&nbsp;println(\"index: \\(index)\")<br \/>\n}<\/codeswift><\/p>\n<p>This is functionally equivalent to our <code>for<\/code> loop example and will result in the same output being printed. In the example above, the closed range operator (<code>...<\/code>) is used to define a collection of numbers from 0 to 4 inclusive. On each iteration, a constant named <code>index<\/code> is created and set with the current value from the range.<\/p>\n<p>By default, a <code>for-in<\/code> loop uses a constant, therefore there is no need to explicitly use the <code>let<\/code> keyword when providing the constant with a name.<\/p>\n<p>As with the <code>for<\/code> loop, block scope is important. The <code>for-in<\/code> loop's constant only exists within the scope of the loop.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Once again, write a program that calculates the sum of numbers between 1 and 100 inclusive. This time, use a <code>for-in<\/code> loop rather than a <code>for<\/code> loop.<br \/>\n <\/div><\/div>\n<h2>If Statements<\/h2>\n<p>Swift provides two types of conditional statements: the <code>if<\/code> statement and the <code>switch<\/code> statement. We'll discuss the <code>switch<\/code> statement in a future article and focus on the various flavours of the <code>if<\/code> statement at the moment since they are more commonly used.<\/p>\n<h3>If Statement<\/h3>\n<p>The <code>if<\/code> statement, like much of the Swift language, will look familiar to anyone who has programmed before. Here it is in its simplest form:<\/p>\n<p><codeswift>var energy = 40<br \/>\nif energy == 0 {<br \/>\n&nbsp;&nbsp;println(\"Vader's lightsaber cuts through you.\")<br \/>\n}<\/codeswift><\/p>\n<p>As with <code>for<\/code> loops, parentheses aren't required when working with <code>if<\/code> statements.<\/p>\n<h3>If-Else Statement<\/h3>\n<p>Of course, you can add an <strong><i>else clause<\/i><\/strong> to your <code>if<\/code> statement:<\/p>\n<p><codeswift>var energy = 40<br \/>\nif energy > 0 {<br \/>\n&nbsp;&nbsp;println(\"The force is strong with you.\")<br \/>\n} else {<br \/>\n&nbsp;&nbsp;println(\"Vader's lightsaber cuts through you.\")<br \/>\n}<\/codeswift><\/p>\n<h3>If-Else If-Else Statement<\/h3>\n<p>Additional clauses can be considered by using the <code>else if<\/code> keywords:<\/p>\n<p><codeswift>var energy = 40<br \/>\nif energy > 40 {<br \/>\n&nbsp;&nbsp;println(\"The force is strong with you.\")<br \/>\n} else if energy > 20 {<br \/>\n&nbsp;&nbsp;println(\"You have much to learn.\")<br \/>\n} else if energy > 0 {<br \/>\n&nbsp;&nbsp;println(\"Your powers are weak old man.\")<br \/>\n} else {<br \/>\n&nbsp;&nbsp;println(\"Vader's lightsaber cuts through you.\")<br \/>\n}<\/codeswift><\/p>\n<p>The final <code>else<\/code> clause isn't mandatory and can be dropped.<\/p>\n<h2>Next Time<\/h2>\n<p>I hope you've found from this tutorial that there's nothing particularly difficult about the Swift programming language. No matter what your development background is, everything covered (perhaps with the exception of optionals) should have felt familiar. We're certainly not in a position to go ahead and get something running on a device yet, but stick with this series and we will get there.<\/p>\n<p>In the next tutorial we'll take a look at Swift's two collection types: arrays and dictionaries. We'll also take a closer look at a few subjects that we touched upon today. Specifically, we'll spend more time looking at strings, and also cover a few more control flow statements including while loops and the <code>switch<\/code> statement.<\/p>\n<p>In the meantime keep experimenting with playgrounds. If there are things that you haven't quite grasped then spend a little time going back over this tutorial and trying things out until they're clear in your head.<\/p>\n<p>See you in <a href=\"?p=324\">part two<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Dive into the Swift programming language with this quick start guide that will have you up and running in no time. What you will learn&#8230; How to work with playgrounds The basics of the Swift programming language Grouping multiple values into a tuple How to work with optionals String fundamentals Control flow What you should [&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-522","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"_links":{"self":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/522","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=522"}],"version-history":[{"count":41,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/522\/revisions"}],"predecessor-version":[{"id":1051,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/522\/revisions\/1051"}],"wp:attachment":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=522"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=522"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=522"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}