khenid

Untitled

Dec 23rd, 2014
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 116.44 KB | None | 0 0
  1.  
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <title>The Swift Programming Language: The Basics</title>
  6. <link rel="stylesheet" type="text/css" href="style-1.2.0.css" />
  7. <link rel="stylesheet" type="text/css" href="feedback-1.2.0.css" />
  8. <meta charset='utf-8'>
  9. </head>
  10.  
  11. <body id="conceptual_flow_with_tasks" class="jazz">
  12.  
  13.  
  14.  
  15. <div class="content-wrapper">
  16.  
  17. <article class="chapter">
  18. <a name="//apple_ref/doc/uid/TP40014097-CH5"></a><a name="//apple_ref/doc/uid/TP40014097-CH5-XID_467"></a>
  19. <a name="//apple_ref/doc/uid/TP40014097-CH4"></a><a name="//apple_ref/doc/uid/TP40014097-CH4-XID_355"></a>
  20.  
  21. <h2 class='chapter-name'>The Basics</h2>
  22.  
  23.  
  24.  
  25. <section class="section">
  26. <p class="para">
  27. Swift is a new programming language for iOS and OS X app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C.
  28. </p>
  29. <p class="para">
  30. Swift provides its own versions of all fundamental C and Objective-C types, including <code class="code-voice">Int</code> for integers, <code class="code-voice">Double</code> and <code class="code-voice">Float</code> for floating-point values, <code class="code-voice">Bool</code> for Boolean values, and <code class="code-voice">String</code> for textual data. Swift also provides powerful versions of the two primary collection types, <code class="code-voice">Array</code> and <code class="code-voice">Dictionary</code>, as described in <span class="x-name"><a href="CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_167" data-id="//apple_ref/doc/uid/TP40014097-CH8-XID_167">Collection Types</a></span>.
  31. </p>
  32. <p class="para">
  33. Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that do not need to change.
  34. </p>
  35. <p class="para">
  36. In addition to familiar types, Swift introduces advanced types not found in Objective-C, such as tuples. Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value.
  37. </p>
  38. <p class="para">
  39. Swift also introduces optional types, which handle the absence of a value. Optionals say either “there <em>is</em> a value, and it equals <em>x</em>” or “there <em>isn’t</em> a value at all”. Optionals are similar to using <code class="code-voice">nil</code> with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than <code class="code-voice">nil</code> pointers in Objective-C and are at the heart of many of Swift’s most powerful features.
  40. </p>
  41. <p class="para">
  42. Optionals are an example of the fact that Swift is a <em>type safe</em> language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a <code class="code-voice">String</code>, type safety prevents you from passing it an <code class="code-voice">Int</code> by mistake. This restriction enables you to catch and fix errors as early as possible in the development process.
  43. </p>
  44.  
  45. </section>
  46.  
  47.  
  48. <section class="section">
  49. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_468"></a>
  50. <h3 class="section-name" tabindex="0">Constants and Variables</h3>
  51. <p class="para">
  52. Constants and variables associate a name (such as <code class="code-voice">maximumNumberOfLoginAttempts</code> or <code class="code-voice">welcomeMessage</code>) with a value of a particular type (such as the number <code class="code-voice">10</code> or the string <code class="code-voice">&quot;Hello&quot;</code>). The value of a <em>constant</em> cannot be changed once it is set, whereas a <em>variable</em> can be set to a different value in the future.
  53. </p>
  54. <section class="section">
  55. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_469"></a>
  56. <h3 class="section-name" tabindex="0">Declaring Constants and Variables</h3>
  57. <p class="para">
  58. Constants and variables must be declared before they are used. You declare constants with the <code class="code-voice">let</code> keyword and variables with the <code class="code-voice">var</code> keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:
  59. </p><section class="code-listing">
  60.  
  61. <span class="caption"></span>
  62. <div class="code-sample">
  63.  
  64. <ul class="code-lines">
  65. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">maximumNumberOfLoginAttempts</span> = <span class="m">10</span></code></li>
  66. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">currentLoginAttempt</span> = <span class="m">0</span></code></li>
  67. </ul>
  68.  
  69.  
  70.  
  71. </div>
  72. </section><p class="para">
  73. This code can be read as:
  74. </p><p class="para">
  75. “Declare a new constant called <code class="code-voice">maximumNumberOfLoginAttempts</code>, and give it a value of <code class="code-voice">10</code>. Then, declare a new variable called <code class="code-voice">currentLoginAttempt</code>, and give it an initial value of <code class="code-voice">0</code>.”
  76. </p><p class="para">
  77. In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt.
  78. </p><p class="para">
  79. You can declare multiple constants or multiple variables on a single line, separated by commas:
  80. </p><section class="code-listing">
  81.  
  82. <span class="caption"></span>
  83. <div class="code-sample">
  84.  
  85. <ul class="code-lines">
  86. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">x</span> = <span class="m">0.0</span>, <span class="vc">y</span> = <span class="m">0.0</span>, <span class="vc">z</span> = <span class="m">0.0</span></code></li>
  87. </ul>
  88.  
  89.  
  90.  
  91. </div>
  92. </section><div class="note">
  93. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_470"></a>
  94. <aside class="aside">
  95. <p class="aside-title">Note
  96. </p>
  97. <p class="para">If a stored value in your code is not going to change, always declare it as a constant with the <code class="code-voice">let</code> keyword. Use variables only for storing values that need to be able to change.
  98. </p>
  99.  
  100. </aside>
  101. </div>
  102.  
  103. </section>
  104. <section class="section">
  105. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_471"></a>
  106. <h3 class="section-name" tabindex="0">Type Annotations</h3>
  107. <p class="para">
  108. You can provide a <em>type annotation</em> when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.
  109. </p><p class="para">
  110. This example provides a type annotation for a variable called <code class="code-voice">welcomeMessage</code>, to indicate that the variable can store <code class="code-voice">String</code> values:
  111. </p><section class="code-listing">
  112.  
  113. <span class="caption"></span>
  114. <div class="code-sample">
  115.  
  116. <ul class="code-lines">
  117. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">welcomeMessage</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span></code></li>
  118. </ul>
  119.  
  120.  
  121.  
  122. </div>
  123. </section><p class="para">
  124. The colon in the declaration means <em>“…of type…,”</em> so the code above can be read as:
  125. </p><p class="para">
  126. “Declare a variable called <code class="code-voice">welcomeMessage</code> that is of type <code class="code-voice">String</code>.”
  127. </p><p class="para">
  128. The phrase “of type <code class="code-voice">String</code>” means “can store any <code class="code-voice">String</code> value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.
  129. </p><p class="para">
  130. The <code class="code-voice">welcomeMessage</code> variable can now be set to any string value without error:
  131. </p><section class="code-listing">
  132.  
  133. <span class="caption"></span>
  134. <div class="code-sample">
  135.  
  136. <ul class="code-lines">
  137. <li><code class="code-voice"><span class="vc">welcomeMessage</span> = <span class="s">&quot;Hello&quot;</span></code></li>
  138. </ul>
  139.  
  140.  
  141.  
  142. </div>
  143. </section><p class="para">
  144. You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:
  145. </p><section class="code-listing">
  146.  
  147. <span class="caption"></span>
  148. <div class="code-sample">
  149.  
  150. <ul class="code-lines">
  151. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">red</span>, <span class="vc">green</span>, <span class="vc">blue</span>: <span class="n"><!-- a href="" -->Double<!-- /a --></span></code></li>
  152. </ul>
  153.  
  154.  
  155.  
  156. </div>
  157. </section><div class="note">
  158. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_472"></a>
  159. <aside class="aside">
  160. <p class="aside-title">Note
  161. </p>
  162. <p class="para">It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in <span class="x-name"><a href="#//apple_ref/doc/uid/TP40014097-CH5-XID_486" data-id="//apple_ref/doc/uid/TP40014097-CH5-XID_486">Type Safety and Type Inference</a></span>. In the <code class="code-voice">welcomeMessage</code> example above, no initial value is provided, and so the type of the <code class="code-voice">welcomeMessage</code> variable is specified with a type annotation rather than being inferred from an initial value.
  163. </p>
  164.  
  165. </aside>
  166. </div>
  167.  
  168. </section>
  169. <section class="section">
  170. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_473"></a>
  171. <h3 class="section-name" tabindex="0">Naming Constants and Variables</h3>
  172. <p class="para">
  173. Constant and variable names can contain almost any character, including Unicode characters:
  174. </p><section class="code-listing">
  175.  
  176. <span class="caption"></span>
  177. <div class="code-sample">
  178.  
  179. <ul class="code-lines">
  180. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">π</span> = <span class="m">3.14159</span></code></li>
  181. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">你好</span> = <span class="s">&quot;你好世界&quot;</span></code></li>
  182. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">🐶🐮</span> = <span class="s">&quot;dogcow&quot;</span></code></li>
  183. </ul>
  184.  
  185.  
  186.  
  187. </div>
  188. </section><p class="para">
  189. Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.
  190. </p><p class="para">
  191. Once you’ve declared a constant or variable of a certain type, you can’t redeclare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant.
  192. </p><div class="note">
  193. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_474"></a>
  194. <aside class="aside">
  195. <p class="aside-title">Note
  196. </p>
  197. <p class="para">If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with back ticks (<code class="code-voice">`</code>) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.
  198. </p>
  199.  
  200. </aside>
  201. </div><p class="para">
  202. You can change the value of an existing variable to another value of a compatible type. In this example, the value of <code class="code-voice">friendlyWelcome</code> is changed from <code class="code-voice">&quot;Hello!&quot;</code> to <code class="code-voice">&quot;Bonjour!&quot;</code>:
  203. </p><section class="code-listing">
  204.  
  205. <span class="caption"></span>
  206. <div class="code-sample">
  207.  
  208. <ul class="code-lines">
  209. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">friendlyWelcome</span> = <span class="s">&quot;Hello!&quot;</span></code></li>
  210. <li><code class="code-voice"><span class="vc">friendlyWelcome</span> = <span class="s">&quot;Bonjour!&quot;</span></code></li>
  211. <li><code class="code-voice"><span class="c">// friendlyWelcome is now &quot;Bonjour!&quot;</span></code></li>
  212. </ul>
  213.  
  214.  
  215.  
  216. </div>
  217. </section><p class="para">
  218. Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled:
  219. </p><section class="code-listing">
  220.  
  221. <span class="caption"></span>
  222. <div class="code-sample">
  223.  
  224. <ul class="code-lines">
  225. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">languageName</span> = <span class="s">&quot;Swift&quot;</span></code></li>
  226. <li><code class="code-voice"><span class="vc">languageName</span> = <span class="s">&quot;Swift++&quot;</span></code></li>
  227. <li><code class="code-voice"><span class="c">// this is a compile-time error - languageName cannot be changed</span></code></li>
  228. </ul>
  229.  
  230.  
  231.  
  232. </div>
  233. </section>
  234.  
  235. </section>
  236. <section class="section">
  237. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_475"></a>
  238. <h3 class="section-name" tabindex="0">Printing Constants and Variables</h3>
  239. <p class="para">
  240. You can print the current value of a constant or variable with the <code class="code-voice">println</code> function:
  241. </p><section class="code-listing">
  242.  
  243. <span class="caption"></span>
  244. <div class="code-sample">
  245.  
  246. <ul class="code-lines">
  247. <li><code class="code-voice"><span class="vc">println</span>(<span class="vc">friendlyWelcome</span>)</code></li>
  248. <li><code class="code-voice"><span class="c">// prints &quot;Bonjour!&quot;</span></code></li>
  249. </ul>
  250.  
  251.  
  252.  
  253. </div>
  254. </section><p class="para">
  255. <code class="code-voice">println</code> is a global function that prints a value, followed by a line break, to an appropriate output. In Xcode, for example, <code class="code-voice">println</code> prints its output in Xcode’s “console” pane. (A second function, <code class="code-voice">print</code>, performs the same task without appending a line break to the end of the value to be printed.)
  256. </p><p class="para">
  257. The <code class="code-voice">println</code> function prints any <code class="code-voice">String</code> value you pass to it:
  258. </p><section class="code-listing">
  259.  
  260. <span class="caption"></span>
  261. <div class="code-sample">
  262.  
  263. <ul class="code-lines">
  264. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;This is a string&quot;</span>)</code></li>
  265. <li><code class="code-voice"><span class="c">// prints &quot;This is a string&quot;</span></code></li>
  266. </ul>
  267.  
  268.  
  269.  
  270. </div>
  271. </section><p class="para">
  272. The <code class="code-voice">println</code> function can print more complex logging messages, in a similar manner to Cocoa’s <code class="code-voice">NSLog</code> function. These messages can include the current values of constants and variables.
  273. </p><p class="para">
  274. Swift uses <em>string interpolation</em> to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis:
  275. </p><section class="code-listing">
  276.  
  277. <span class="caption"></span>
  278. <div class="code-sample">
  279.  
  280. <ul class="code-lines">
  281. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The current value of friendlyWelcome is </span>\(<span class="vc">friendlyWelcome</span>)<span class="s">&quot;</span>)</code></li>
  282. <li><code class="code-voice"><span class="c">// prints &quot;The current value of friendlyWelcome is Bonjour!&quot;</span></code></li>
  283. </ul>
  284.  
  285.  
  286.  
  287. </div>
  288. </section><div class="note">
  289. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_476"></a>
  290. <aside class="aside">
  291. <p class="aside-title">Note
  292. </p>
  293. <p class="para">All options you can use with string interpolation are described in <span class="x-name"><a href="StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_443" data-id="//apple_ref/doc/uid/TP40014097-CH7-XID_443">String Interpolation</a></span>.
  294. </p>
  295.  
  296. </aside>
  297. </div>
  298.  
  299. </section>
  300.  
  301. </section>
  302. <section class="section">
  303. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_477"></a>
  304. <h3 class="section-name" tabindex="0">Comments</h3>
  305. <p class="para">
  306. Use comments to include non-executable text in your code, as a note or reminder to yourself. Comments are ignored by the Swift compiler when your code is compiled.
  307. </p><p class="para">
  308. Comments in Swift are very similar to comments in C. Single-line comments begin with two forward-slashes (<code class="code-voice">//</code>):
  309. </p><section class="code-listing">
  310.  
  311. <span class="caption"></span>
  312. <div class="code-sample">
  313.  
  314. <ul class="code-lines">
  315. <li><code class="code-voice"><span class="c">// this is a comment</span></code></li>
  316. </ul>
  317.  
  318.  
  319.  
  320. </div>
  321. </section><p class="para">
  322. Multiline comments start with a forward-slash followed by an asterisk (<code class="code-voice">/*</code>) and end with an asterisk followed by a forward-slash (<code class="code-voice">*/</code>):
  323. </p><section class="code-listing">
  324.  
  325. <span class="caption"></span>
  326. <div class="code-sample">
  327.  
  328. <ul class="code-lines">
  329. <li><code class="code-voice"><span class="c">/* this is also a comment,</span></code></li>
  330. <li><code class="code-voice"><span class="c">but written over multiple lines */</span></code></li>
  331. </ul>
  332.  
  333.  
  334.  
  335. </div>
  336. </section><p class="para">
  337. Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:
  338. </p><section class="code-listing">
  339.  
  340. <span class="caption"></span>
  341. <div class="code-sample">
  342.  
  343. <ul class="code-lines">
  344. <li><code class="code-voice"><span class="c">/* this is the start of the first multiline comment</span></code></li>
  345. <li><code class="code-voice"><span class="c">/* this is the second, nested multiline comment */</span></code></li>
  346. <li><code class="code-voice"><span class="c">this is the end of the first multiline comment */</span></code></li>
  347. </ul>
  348.  
  349.  
  350.  
  351. </div>
  352. </section><p class="para">
  353. Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.
  354. </p>
  355.  
  356. </section>
  357. <section class="section">
  358. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_478"></a>
  359. <h3 class="section-name" tabindex="0">Semicolons</h3>
  360. <p class="para">
  361. Unlike many other languages, Swift does not require you to write a semicolon (<code class="code-voice">;</code>) after each statement in your code, although you can do so if you wish. Semicolons <em>are</em> required, however, if you want to write multiple separate statements on a single line:
  362. </p><section class="code-listing">
  363.  
  364. <span class="caption"></span>
  365. <div class="code-sample">
  366.  
  367. <ul class="code-lines">
  368. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">cat</span> = <span class="s">&quot;🐱&quot;</span>; <span class="vc">println</span>(<span class="vc">cat</span>)</code></li>
  369. <li><code class="code-voice"><span class="c">// prints &quot;🐱&quot;</span></code></li>
  370. </ul>
  371.  
  372.  
  373.  
  374. </div>
  375. </section>
  376.  
  377. </section>
  378. <section class="section">
  379. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_479"></a>
  380. <h3 class="section-name" tabindex="0">Integers</h3>
  381. <p class="para">
  382. <em>Integers</em> are whole numbers with no fractional component, such as <code class="code-voice">42</code> and <code class="code-voice">-23</code>. Integers are either <em>signed</em> (positive, zero, or negative) or <em>unsigned</em> (positive or zero).
  383. </p><p class="para">
  384. Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type <code class="code-voice">UInt8</code>, and a 32-bit signed integer is of type <code class="code-voice">Int32</code>. Like all types in Swift, these integer types have capitalized names.
  385. </p>
  386. <section class="section">
  387. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_480"></a>
  388. <h3 class="section-name" tabindex="0">Integer Bounds</h3>
  389. <p class="para">
  390. You can access the minimum and maximum values of each integer type with its <code class="code-voice">min</code> and <code class="code-voice">max</code> properties:
  391. </p><section class="code-listing">
  392.  
  393. <span class="caption"></span>
  394. <div class="code-sample">
  395.  
  396. <ul class="code-lines">
  397. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">minValue</span> = <span class="vc">UInt8</span>.<span class="vc">min</span> <span class="c">// minValue is equal to 0, and is of type UInt8</span></code></li>
  398. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">maxValue</span> = <span class="vc">UInt8</span>.<span class="vc">max</span> <span class="c">// maxValue is equal to 255, and is of type UInt8</span></code></li>
  399. </ul>
  400.  
  401.  
  402.  
  403. </div>
  404. </section><p class="para">
  405. The values of these properties are of the appropriate-sized number type (such as <code class="code-voice">UInt8</code> in the example above) and can therefore be used in expressions alongside other values of the same type.
  406. </p>
  407.  
  408. </section>
  409. <section class="section">
  410. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_481"></a>
  411. <h3 class="section-name" tabindex="0">Int</h3>
  412. <p class="para">
  413. In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, <code class="code-voice">Int</code>, which has the same size as the current platform’s native word size:
  414. </p><ul class="list-bullet">
  415. <li class="item"><p class="para">
  416. On a 32-bit platform, <code class="code-voice">Int</code> is the same size as <code class="code-voice">Int32</code>.
  417. </p>
  418. </li><li class="item"><p class="para">
  419. On a 64-bit platform, <code class="code-voice">Int</code> is the same size as <code class="code-voice">Int64</code>.
  420. </p>
  421. </li>
  422. </ul><p class="para">
  423. Unless you need to work with a specific size of integer, always use <code class="code-voice">Int</code> for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, <code class="code-voice">Int</code> can store any value between <code class="code-voice">-2,147,483,648</code> and <code class="code-voice">2,147,483,647</code>, and is large enough for many integer ranges.
  424. </p>
  425.  
  426. </section>
  427. <section class="section">
  428. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_482"></a>
  429. <h3 class="section-name" tabindex="0">UInt</h3>
  430. <p class="para">
  431. Swift also provides an unsigned integer type, <code class="code-voice">UInt</code>, which has the same size as the current platform’s native word size:
  432. </p><ul class="list-bullet">
  433. <li class="item"><p class="para">
  434. On a 32-bit platform, <code class="code-voice">UInt</code> is the same size as <code class="code-voice">UInt32</code>.
  435. </p>
  436. </li><li class="item"><p class="para">
  437. On a 64-bit platform, <code class="code-voice">UInt</code> is the same size as <code class="code-voice">UInt64</code>.
  438. </p>
  439. </li>
  440. </ul><div class="note">
  441. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_483"></a>
  442. <aside class="aside">
  443. <p class="aside-title">Note
  444. </p>
  445. <p class="para">Use <code class="code-voice">UInt</code> only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case, <code class="code-voice">Int</code> is preferred, even when the values to be stored are known to be non-negative. A consistent use of <code class="code-voice">Int</code> for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in <span class="x-name"><a href="#//apple_ref/doc/uid/TP40014097-CH5-XID_486" data-id="//apple_ref/doc/uid/TP40014097-CH5-XID_486">Type Safety and Type Inference</a></span>.
  446. </p>
  447.  
  448. </aside>
  449. </div>
  450.  
  451. </section>
  452.  
  453. </section>
  454. <section class="section">
  455. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_484"></a>
  456. <h3 class="section-name" tabindex="0">Floating-Point Numbers</h3>
  457. <p class="para">
  458. <em>Floating-point numbers</em> are numbers with a fractional component, such as <code class="code-voice">3.14159</code>, <code class="code-voice">0.1</code>, and <code class="code-voice">-273.15</code>.
  459. </p><p class="para">
  460. Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an <code class="code-voice">Int</code>. Swift provides two signed floating-point number types:
  461. </p><ul class="list-bullet">
  462. <li class="item"><p class="para">
  463. <code class="code-voice">Double</code> represents a 64-bit floating-point number. Use it when floating-point values must be very large or particularly precise.
  464. </p>
  465. </li><li class="item"><p class="para">
  466. <code class="code-voice">Float</code> represents a 32-bit floating-point number. Use it when floating-point values do not require 64-bit precision.
  467. </p>
  468. </li>
  469. </ul><div class="note">
  470. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_485"></a>
  471. <aside class="aside">
  472. <p class="aside-title">Note
  473. </p>
  474. <p class="para"><code class="code-voice">Double</code> has a precision of at least 15 decimal digits, whereas the precision of <code class="code-voice">Float</code> can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code.
  475. </p>
  476.  
  477. </aside>
  478. </div>
  479.  
  480. </section>
  481. <section class="section">
  482. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_486"></a>
  483. <h3 class="section-name" tabindex="0">Type Safety and Type Inference</h3>
  484. <p class="para">
  485. Swift is a <em>type safe</em> language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a <code class="code-voice">String</code>, you can’t pass it an <code class="code-voice">Int</code> by mistake.
  486. </p><p class="para">
  487. Because Swift is type safe, it performs <em>type checks</em> when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process.
  488. </p><p class="para">
  489. Type-checking helps you avoid errors when you’re working with different types of values. However, this doesn’t mean that you have to specify the type of every constant and variable that you declare. If you don’t specify the type of value you need, Swift uses <em>type inference</em> to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.
  490. </p><p class="para">
  491. Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C. Constants and variables are still explicitly typed, but much of the work of specifying their type is done for you.
  492. </p><p class="para">
  493. Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a <em>literal value</em> (or <em>literal</em>) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as <code class="code-voice">42</code> and <code class="code-voice">3.14159</code> in the examples below.)
  494. </p><p class="para">
  495. For example, if you assign a literal value of <code class="code-voice">42</code> to a new constant without saying what type it is, Swift infers that you want the constant to be an <code class="code-voice">Int</code>, because you have initialized it with a number that looks like an integer:
  496. </p><section class="code-listing">
  497.  
  498. <span class="caption"></span>
  499. <div class="code-sample">
  500.  
  501. <ul class="code-lines">
  502. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">meaningOfLife</span> = <span class="m">42</span></code></li>
  503. <li><code class="code-voice"><span class="c">// meaningOfLife is inferred to be of type Int</span></code></li>
  504. </ul>
  505.  
  506.  
  507.  
  508. </div>
  509. </section><p class="para">
  510. Likewise, if you don’t specify a type for a floating-point literal, Swift infers that you want to create a <code class="code-voice">Double</code>:
  511. </p><section class="code-listing">
  512.  
  513. <span class="caption"></span>
  514. <div class="code-sample">
  515.  
  516. <ul class="code-lines">
  517. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">pi</span> = <span class="m">3.14159</span></code></li>
  518. <li><code class="code-voice"><span class="c">// pi is inferred to be of type Double</span></code></li>
  519. </ul>
  520.  
  521.  
  522.  
  523. </div>
  524. </section><p class="para">
  525. Swift always chooses <code class="code-voice">Double</code> (rather than <code class="code-voice">Float</code>) when inferring the type of floating-point numbers.
  526. </p><p class="para">
  527. If you combine integer and floating-point literals in an expression, a type of <code class="code-voice">Double</code> will be inferred from the context:
  528. </p><section class="code-listing">
  529.  
  530. <span class="caption"></span>
  531. <div class="code-sample">
  532.  
  533. <ul class="code-lines">
  534. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">anotherPi</span> = <span class="m">3</span> + <span class="m">0.14159</span></code></li>
  535. <li><code class="code-voice"><span class="c">// anotherPi is also inferred to be of type Double</span></code></li>
  536. </ul>
  537.  
  538.  
  539.  
  540. </div>
  541. </section><p class="para">
  542. The literal value of <code class="code-voice">3</code> has no explicit type in and of itself, and so an appropriate output type of <code class="code-voice">Double</code> is inferred from the presence of a floating-point literal as part of the addition.
  543. </p>
  544.  
  545. </section>
  546. <section class="section">
  547. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_487"></a>
  548. <h3 class="section-name" tabindex="0">Numeric Literals</h3>
  549. <p class="para">
  550. Integer literals can be written as:
  551. </p><ul class="list-bullet">
  552. <li class="item"><p class="para">
  553. A <em>decimal</em> number, with no prefix
  554. </p>
  555. </li><li class="item"><p class="para">
  556. A <em>binary</em> number, with a <code class="code-voice">0b</code> prefix
  557. </p>
  558. </li><li class="item"><p class="para">
  559. An <em>octal</em> number, with a <code class="code-voice">0o</code> prefix
  560. </p>
  561. </li><li class="item"><p class="para">
  562. A <em>hexadecimal</em> number, with a <code class="code-voice">0x</code> prefix
  563. </p>
  564. </li>
  565. </ul><p class="para">
  566. All of these integer literals have a decimal value of <code class="code-voice">17</code>:
  567. </p><section class="code-listing">
  568.  
  569. <span class="caption"></span>
  570. <div class="code-sample">
  571.  
  572. <ul class="code-lines">
  573. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">decimalInteger</span> = <span class="m">17</span></code></li>
  574. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">binaryInteger</span> = <span class="m">0b10001</span> <span class="c">// 17 in binary notation</span></code></li>
  575. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">octalInteger</span> = <span class="m">0o21</span> <span class="c">// 17 in octal notation</span></code></li>
  576. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">hexadecimalInteger</span> = <span class="m">0x11</span> <span class="c">// 17 in hexadecimal notation</span></code></li>
  577. </ul>
  578.  
  579.  
  580.  
  581. </div>
  582. </section><p class="para">
  583. Floating-point literals can be decimal (with no prefix), or hexadecimal (with a <code class="code-voice">0x</code> prefix). They must always have a number (or hexadecimal number) on both sides of the decimal point. They can also have an optional <em>exponent</em>, indicated by an uppercase or lowercase <code class="code-voice">e</code> for decimal floats, or an uppercase or lowercase <code class="code-voice">p</code> for hexadecimal floats.
  584. </p><p class="para">
  585. For decimal numbers with an exponent of <code class="code-voice">exp</code>, the base number is multiplied by 10<sup>exp</sup>:
  586. </p><ul class="list-bullet">
  587. <li class="item"><p class="para">
  588. <code class="code-voice">1.25e2</code> means 1.25 × 10<sup>2</sup>, or <code class="code-voice">125.0</code>.
  589. </p>
  590. </li><li class="item"><p class="para">
  591. <code class="code-voice">1.25e-2</code> means 1.25 × 10<sup>-2</sup>, or <code class="code-voice">0.0125</code>.
  592. </p>
  593. </li>
  594. </ul><p class="para">
  595. For hexadecimal numbers with an exponent of <code class="code-voice">exp</code>, the base number is multiplied by 2<sup>exp</sup>:
  596. </p><ul class="list-bullet">
  597. <li class="item"><p class="para">
  598. <code class="code-voice">0xFp2</code> means 15 × 2<sup>2</sup>, or <code class="code-voice">60.0</code>.
  599. </p>
  600. </li><li class="item"><p class="para">
  601. <code class="code-voice">0xFp-2</code> means 15 × 2<sup>-2</sup>, or <code class="code-voice">3.75</code>.
  602. </p>
  603. </li>
  604. </ul><p class="para">
  605. All of these floating-point literals have a decimal value of <code class="code-voice">12.1875</code>:
  606. </p><section class="code-listing">
  607.  
  608. <span class="caption"></span>
  609. <div class="code-sample">
  610.  
  611. <ul class="code-lines">
  612. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">decimalDouble</span> = <span class="m">12.1875</span></code></li>
  613. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">exponentDouble</span> = <span class="m">1.21875e1</span></code></li>
  614. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">hexadecimalDouble</span> = <span class="m">0xC.3p0</span></code></li>
  615. </ul>
  616.  
  617.  
  618.  
  619. </div>
  620. </section><p class="para">
  621. Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeroes and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:
  622. </p><section class="code-listing">
  623.  
  624. <span class="caption"></span>
  625. <div class="code-sample">
  626.  
  627. <ul class="code-lines">
  628. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">paddedDouble</span> = <span class="m">000123.456</span></code></li>
  629. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">oneMillion</span> = <span class="m">1_000_000</span></code></li>
  630. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">justOverOneMillion</span> = <span class="m">1_000_000.000_000_1</span></code></li>
  631. </ul>
  632.  
  633.  
  634.  
  635. </div>
  636. </section>
  637.  
  638. </section>
  639. <section class="section">
  640. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_488"></a>
  641. <h3 class="section-name" tabindex="0">Numeric Type Conversion</h3>
  642. <p class="para">
  643. Use the <code class="code-voice">Int</code> type for all general-purpose integer constants and variables in your code, even if they are known to be non-negative. Using the default integer type in everyday situations means that integer constants and variables are immediately interoperable in your code and will match the inferred type for integer literal values.
  644. </p><p class="para">
  645. Use other integer types only when they are specifically needed for the task at hand, because of explicitly-sized data from an external source, or for performance, memory usage, or other necessary optimization. Using explicitly-sized types in these situations helps to catch any accidental value overflows and implicitly documents the nature of the data being used.
  646. </p>
  647. <section class="section">
  648. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_489"></a>
  649. <h3 class="section-name" tabindex="0">Integer Conversion</h3>
  650. <p class="para">
  651. The range of numbers that can be stored in an integer constant or variable is different for each numeric type. An <code class="code-voice">Int8</code> constant or variable can store numbers between <code class="code-voice">-128</code> and <code class="code-voice">127</code>, whereas a <code class="code-voice">UInt8</code> constant or variable can store numbers between <code class="code-voice">0</code> and <code class="code-voice">255</code>. A number that will not fit into a constant or variable of a sized integer type is reported as an error when your code is compiled:
  652. </p><section class="code-listing">
  653.  
  654. <span class="caption"></span>
  655. <div class="code-sample">
  656.  
  657. <ul class="code-lines">
  658. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">cannotBeNegative</span>: <span class="n"><!-- a href="" -->UInt8<!-- /a --></span> = -<span class="m">1</span></code></li>
  659. <li><code class="code-voice"><span class="c">// UInt8 cannot store negative numbers, and so this will report an error</span></code></li>
  660. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">tooBig</span>: <span class="n"><!-- a href="" -->Int8<!-- /a --></span> = <span class="vc">Int8</span>.<span class="vc">max</span> + <span class="m">1</span></code></li>
  661. <li><code class="code-voice"><span class="c">// Int8 cannot store a number larger than its maximum value,</span></code></li>
  662. <li><code class="code-voice"><span class="c">// and so this will also report an error</span></code></li>
  663. </ul>
  664.  
  665.  
  666.  
  667. </div>
  668. </section><p class="para">
  669. Because each numeric type can store a different range of values, you must opt in to numeric type conversion on a case-by-case basis. This opt-in approach prevents hidden conversion errors and helps make type conversion intentions explicit in your code.
  670. </p><p class="para">
  671. To convert one specific number type to another, you initialize a new number of the desired type with the existing value. In the example below, the constant <code class="code-voice">twoThousand</code> is of type <code class="code-voice">UInt16</code>, whereas the constant <code class="code-voice">one</code> is of type <code class="code-voice">UInt8</code>. They cannot be added together directly, because they are not of the same type. Instead, this example calls <code class="code-voice">UInt16(one)</code> to create a new <code class="code-voice">UInt16</code> initialized with the value of <code class="code-voice">one</code>, and uses this value in place of the original:
  672. </p><section class="code-listing">
  673.  
  674. <span class="caption"></span>
  675. <div class="code-sample">
  676.  
  677. <ul class="code-lines">
  678. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">twoThousand</span>: <span class="n"><!-- a href="" -->UInt16<!-- /a --></span> = <span class="m">2_000</span></code></li>
  679. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">one</span>: <span class="n"><!-- a href="" -->UInt8<!-- /a --></span> = <span class="m">1</span></code></li>
  680. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">twoThousandAndOne</span> = <span class="vc">twoThousand</span> + <span class="vc">UInt16</span>(<span class="vc">one</span>)</code></li>
  681. </ul>
  682.  
  683.  
  684.  
  685. </div>
  686. </section><p class="para">
  687. Because both sides of the addition are now of type <code class="code-voice">UInt16</code>, the addition is allowed. The output constant (<code class="code-voice">twoThousandAndOne</code>) is inferred to be of type <code class="code-voice">UInt16</code>, because it is the sum of two <code class="code-voice">UInt16</code> values.
  688. </p><p class="para">
  689. <code class="code-voice">SomeType(ofInitialValue)</code> is the default way to call the initializer of a Swift type and pass in an initial value. Behind the scenes, <code class="code-voice">UInt16</code> has an initializer that accepts a <code class="code-voice">UInt8</code> value, and so this initializer is used to make a new <code class="code-voice">UInt16</code> from an existing <code class="code-voice">UInt8</code>. You can’t pass in <em>any</em> type here, however—it has to be a type for which <code class="code-voice">UInt16</code> provides an initializer. Extending existing types to provide initializers that accept new types (including your own type definitions) is covered in <span class="x-name"><a href="Extensions.html#//apple_ref/doc/uid/TP40014097-CH24-XID_229" data-id="//apple_ref/doc/uid/TP40014097-CH24-XID_229">Extensions</a></span>.
  690. </p>
  691.  
  692. </section>
  693. <section class="section">
  694. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_490"></a>
  695. <h3 class="section-name" tabindex="0">Integer and Floating-Point Conversion</h3>
  696. <p class="para">
  697. Conversions between integer and floating-point numeric types must be made explicit:
  698. </p><section class="code-listing">
  699.  
  700. <span class="caption"></span>
  701. <div class="code-sample">
  702.  
  703. <ul class="code-lines">
  704. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">three</span> = <span class="m">3</span></code></li>
  705. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">pointOneFourOneFiveNine</span> = <span class="m">0.14159</span></code></li>
  706. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">pi</span> = <span class="vc">Double</span>(<span class="vc">three</span>) + <span class="vc">pointOneFourOneFiveNine</span></code></li>
  707. <li><code class="code-voice"><span class="c">// pi equals 3.14159, and is inferred to be of type Double</span></code></li>
  708. </ul>
  709.  
  710.  
  711.  
  712. </div>
  713. </section><p class="para">
  714. Here, the value of the constant <code class="code-voice">three</code> is used to create a new value of type <code class="code-voice">Double</code>, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed.
  715. </p><p class="para">
  716. Floating-point to integer conversion must also be made explicit. An integer type can be initialized with a <code class="code-voice">Double</code> or <code class="code-voice">Float</code> value:
  717. </p><section class="code-listing">
  718.  
  719. <span class="caption"></span>
  720. <div class="code-sample">
  721.  
  722. <ul class="code-lines">
  723. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">integerPi</span> = <span class="vc">Int</span>(<span class="vc">pi</span>)</code></li>
  724. <li><code class="code-voice"><span class="c">// integerPi equals 3, and is inferred to be of type Int</span></code></li>
  725. </ul>
  726.  
  727.  
  728.  
  729. </div>
  730. </section><p class="para">
  731. Floating-point values are always truncated when used to initialize a new integer value in this way. This means that <code class="code-voice">4.75</code> becomes <code class="code-voice">4</code>, and <code class="code-voice">-3.9</code> becomes <code class="code-voice">-3</code>.
  732. </p><div class="note">
  733. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_491"></a>
  734. <aside class="aside">
  735. <p class="aside-title">Note
  736. </p>
  737. <p class="para">The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value <code class="code-voice">3</code> can be added directly to the literal value <code class="code-voice">0.14159</code>, because number literals do not have an explicit type in and of themselves. Their type is inferred only at the point that they are evaluated by the compiler.
  738. </p>
  739.  
  740. </aside>
  741. </div>
  742.  
  743. </section>
  744.  
  745. </section>
  746. <section class="section">
  747. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_492"></a>
  748. <h3 class="section-name" tabindex="0">Type Aliases</h3>
  749. <p class="para">
  750. <em>Type aliases</em> define an alternative name for an existing type. You define type aliases with the <code class="code-voice">typealias</code> keyword.
  751. </p><p class="para">
  752. Type aliases are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source:
  753. </p><section class="code-listing">
  754.  
  755. <span class="caption"></span>
  756. <div class="code-sample">
  757.  
  758. <ul class="code-lines">
  759. <li><code class="code-voice"><span class="kt">typealias</span> <span class="vc">AudioSample</span> = <span class="n"><!-- a href="" -->UInt16<!-- /a --></span></code></li>
  760. </ul>
  761.  
  762.  
  763.  
  764. </div>
  765. </section><p class="para">
  766. Once you define a type alias, you can use the alias anywhere you might use the original name:
  767. </p><section class="code-listing">
  768.  
  769. <span class="caption"></span>
  770. <div class="code-sample">
  771.  
  772. <ul class="code-lines">
  773. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">maxAmplitudeFound</span> = <span class="vc">AudioSample</span>.<span class="vc">min</span></code></li>
  774. <li><code class="code-voice"><span class="c">// maxAmplitudeFound is now 0</span></code></li>
  775. </ul>
  776.  
  777.  
  778.  
  779. </div>
  780. </section><p class="para">
  781. Here, <code class="code-voice">AudioSample</code> is defined as an alias for <code class="code-voice">UInt16</code>. Because it is an alias, the call to <code class="code-voice">AudioSample.min</code> actually calls <code class="code-voice">UInt16.min</code>, which provides an initial value of <code class="code-voice">0</code> for the <code class="code-voice">maxAmplitudeFound</code> variable.
  782. </p>
  783.  
  784. </section>
  785. <section class="section">
  786. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_493"></a>
  787. <h3 class="section-name" tabindex="0">Booleans</h3>
  788. <p class="para">
  789. Swift has a basic <em>Boolean</em> type, called <code class="code-voice">Bool</code>. Boolean values are referred to as <em>logical</em>, because they can only ever be true or false. Swift provides two Boolean constant values, <code class="code-voice">true</code> and <code class="code-voice">false</code>:
  790. </p><section class="code-listing">
  791.  
  792. <span class="caption"></span>
  793. <div class="code-sample">
  794.  
  795. <ul class="code-lines">
  796. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">orangesAreOrange</span> = <span class="kt">true</span></code></li>
  797. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">turnipsAreDelicious</span> = <span class="kt">false</span></code></li>
  798. </ul>
  799.  
  800.  
  801.  
  802. </div>
  803. </section><p class="para">
  804. The types of <code class="code-voice">orangesAreOrange</code> and <code class="code-voice">turnipsAreDelicious</code> have been inferred as <code class="code-voice">Bool</code> from the fact that they were initialized with Boolean literal values. As with <code class="code-voice">Int</code> and <code class="code-voice">Double</code> above, you don’t need to declare constants or variables as <code class="code-voice">Bool</code> if you set them to <code class="code-voice">true</code> or <code class="code-voice">false</code> as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known.
  805. </p><p class="para">
  806. Boolean values are particularly useful when you work with conditional statements such as the <code class="code-voice">if</code> statement:
  807. </p><section class="code-listing">
  808.  
  809. <span class="caption"></span>
  810. <div class="code-sample">
  811.  
  812. <ul class="code-lines">
  813. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">turnipsAreDelicious</span> {</code></li>
  814. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;Mmm, tasty turnips!&quot;</span>)</code></li>
  815. <li><code class="code-voice">} <span class="kt">else</span> {</code></li>
  816. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;Eww, turnips are horrible.&quot;</span>)</code></li>
  817. <li><code class="code-voice">}</code></li>
  818. <li><code class="code-voice"><span class="c">// prints &quot;Eww, turnips are horrible.&quot;</span></code></li>
  819. </ul>
  820.  
  821.  
  822.  
  823. </div>
  824. </section><p class="para">
  825. Conditional statements such as the <code class="code-voice">if</code> statement are covered in more detail in <span class="x-name"><a href="ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_190" data-id="//apple_ref/doc/uid/TP40014097-CH9-XID_190">Control Flow</a></span>.
  826. </p><p class="para">
  827. Swift’s type safety prevents non-Boolean values from being substituted for <code class="code-voice">Bool</code>. The following example reports a compile-time error:
  828. </p><section class="code-listing">
  829.  
  830. <span class="caption"></span>
  831. <div class="code-sample">
  832.  
  833. <ul class="code-lines">
  834. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">i</span> = <span class="m">1</span></code></li>
  835. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">i</span> {</code></li>
  836. <li><code class="code-voice"> <span class="c">// this example will not compile, and will report an error</span></code></li>
  837. <li><code class="code-voice">}</code></li>
  838. </ul>
  839.  
  840.  
  841.  
  842. </div>
  843. </section><p class="para">
  844. However, the alternative example below is valid:
  845. </p><section class="code-listing">
  846.  
  847. <span class="caption"></span>
  848. <div class="code-sample">
  849.  
  850. <ul class="code-lines">
  851. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">i</span> = <span class="m">1</span></code></li>
  852. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">i</span> == <span class="m">1</span> {</code></li>
  853. <li><code class="code-voice"> <span class="c">// this example will compile successfully</span></code></li>
  854. <li><code class="code-voice">}</code></li>
  855. </ul>
  856.  
  857.  
  858.  
  859. </div>
  860. </section><p class="para">
  861. The result of the <code class="code-voice">i == 1</code> comparison is of type <code class="code-voice">Bool</code>, and so this second example passes the type-check. Comparisons like <code class="code-voice">i == 1</code> are discussed in <span class="x-name"><a href="BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-XID_108" data-id="//apple_ref/doc/uid/TP40014097-CH6-XID_108">Basic Operators</a></span>.
  862. </p><p class="para">
  863. As with other examples of type safety in Swift, this approach avoids accidental errors and ensures that the intention of a particular section of code is always clear.
  864. </p>
  865.  
  866. </section>
  867. <section class="section">
  868. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_494"></a>
  869. <h3 class="section-name" tabindex="0">Tuples</h3>
  870. <p class="para">
  871. <em>Tuples</em> group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
  872. </p><p class="para">
  873. In this example, <code class="code-voice">(404, &quot;Not Found&quot;)</code> is a tuple that describes an <em>HTTP status code</em>. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of <code class="code-voice">404 Not Found</code> is returned if you request a webpage that doesn’t exist.
  874. </p><section class="code-listing">
  875.  
  876. <span class="caption"></span>
  877. <div class="code-sample">
  878.  
  879. <ul class="code-lines">
  880. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">http404Error</span> = (<span class="m">404</span>, <span class="s">&quot;Not Found&quot;</span>)</code></li>
  881. <li><code class="code-voice"><span class="c">// http404Error is of type (Int, String), and equals (404, &quot;Not Found&quot;)</span></code></li>
  882. </ul>
  883.  
  884.  
  885.  
  886. </div>
  887. </section><p class="para">
  888. The <code class="code-voice">(404, &quot;Not Found&quot;)</code> tuple groups together an <code class="code-voice">Int</code> and a <code class="code-voice">String</code> to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type <code class="code-voice">(Int, String)</code>”.
  889. </p><p class="para">
  890. You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type <code class="code-voice">(Int, Int, Int)</code>, or <code class="code-voice">(String, Bool)</code>, or indeed any other permutation you require.
  891. </p><p class="para">
  892. You can <em>decompose</em> a tuple’s contents into separate constants or variables, which you then access as usual:
  893. </p><section class="code-listing">
  894.  
  895. <span class="caption"></span>
  896. <div class="code-sample">
  897.  
  898. <ul class="code-lines">
  899. <li><code class="code-voice"><span class="kt">let</span> (<span class="vc">statusCode</span>, <span class="vc">statusMessage</span>) = <span class="vc">http404Error</span></code></li>
  900. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status code is </span>\(<span class="vc">statusCode</span>)<span class="s">&quot;</span>)</code></li>
  901. <li><code class="code-voice"><span class="c">// prints &quot;The status code is 404&quot;</span></code></li>
  902. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status message is </span>\(<span class="vc">statusMessage</span>)<span class="s">&quot;</span>)</code></li>
  903. <li><code class="code-voice"><span class="c">// prints &quot;The status message is Not Found&quot;</span></code></li>
  904. </ul>
  905.  
  906.  
  907.  
  908. </div>
  909. </section><p class="para">
  910. If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (<code class="code-voice">_</code>) when you decompose the tuple:
  911. </p><section class="code-listing">
  912.  
  913. <span class="caption"></span>
  914. <div class="code-sample">
  915.  
  916. <ul class="code-lines">
  917. <li><code class="code-voice"><span class="kt">let</span> (<span class="vc">justTheStatusCode</span>, <span class="kt">_</span>) = <span class="vc">http404Error</span></code></li>
  918. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status code is </span>\(<span class="vc">justTheStatusCode</span>)<span class="s">&quot;</span>)</code></li>
  919. <li><code class="code-voice"><span class="c">// prints &quot;The status code is 404&quot;</span></code></li>
  920. </ul>
  921.  
  922.  
  923.  
  924. </div>
  925. </section><p class="para">
  926. Alternatively, access the individual element values in a tuple using index numbers starting at zero:
  927. </p><section class="code-listing">
  928.  
  929. <span class="caption"></span>
  930. <div class="code-sample">
  931.  
  932. <ul class="code-lines">
  933. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status code is </span>\(<span class="vc">http404Error</span>.<span class="m">0</span>)<span class="s">&quot;</span>)</code></li>
  934. <li><code class="code-voice"><span class="c">// prints &quot;The status code is 404&quot;</span></code></li>
  935. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status message is </span>\(<span class="vc">http404Error</span>.<span class="m">1</span>)<span class="s">&quot;</span>)</code></li>
  936. <li><code class="code-voice"><span class="c">// prints &quot;The status message is Not Found&quot;</span></code></li>
  937. </ul>
  938.  
  939.  
  940.  
  941. </div>
  942. </section><p class="para">
  943. You can name the individual elements in a tuple when the tuple is defined:
  944. </p><section class="code-listing">
  945.  
  946. <span class="caption"></span>
  947. <div class="code-sample">
  948.  
  949. <ul class="code-lines">
  950. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">http200Status</span> = (<span class="vc">statusCode</span>: <span class="m">200</span>, <span class="vc">description</span>: <span class="s">&quot;OK&quot;</span>)</code></li>
  951. </ul>
  952.  
  953.  
  954.  
  955. </div>
  956. </section><p class="para">
  957. If you name the elements in a tuple, you can use the element names to access the values of those elements:
  958. </p><section class="code-listing">
  959.  
  960. <span class="caption"></span>
  961. <div class="code-sample">
  962.  
  963. <ul class="code-lines">
  964. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status code is </span>\(<span class="vc">http200Status</span>.<span class="vc">statusCode</span>)<span class="s">&quot;</span>)</code></li>
  965. <li><code class="code-voice"><span class="c">// prints &quot;The status code is 200&quot;</span></code></li>
  966. <li><code class="code-voice"><span class="vc">println</span>(<span class="s">&quot;The status message is </span>\(<span class="vc">http200Status</span>.<span class="vc">description</span>)<span class="s">&quot;</span>)</code></li>
  967. <li><code class="code-voice"><span class="c">// prints &quot;The status message is OK&quot;</span></code></li>
  968. </ul>
  969.  
  970.  
  971.  
  972. </div>
  973. </section><p class="para">
  974. Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the <code class="code-voice">(Int, String)</code> tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. For more information, see <span class="x-name"><a href="Functions.html#//apple_ref/doc/uid/TP40014097-CH10-XID_251" data-id="//apple_ref/doc/uid/TP40014097-CH10-XID_251">Functions with Multiple Return Values</a></span>.
  975. </p><div class="note">
  976. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_495"></a>
  977. <aside class="aside">
  978. <p class="aside-title">Note
  979. </p>
  980. <p class="para">Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information, see <span class="x-name"><a href="ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_134" data-id="//apple_ref/doc/uid/TP40014097-CH13-XID_134">Classes and Structures</a></span>.
  981. </p>
  982.  
  983. </aside>
  984. </div>
  985.  
  986. </section>
  987. <section class="section">
  988. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_496"></a>
  989. <h3 class="section-name" tabindex="0">Optionals</h3>
  990. <p class="para">
  991. You use <em>optionals</em> in situations where a value may be absent. An optional says:
  992. </p><ul class="list-bullet">
  993. <li class="item"><p class="para">
  994. There <em>is</em> a value, and it equals <em>x</em>
  995. </p>
  996. </li>
  997. </ul><p class="para">
  998. <em>or</em>
  999. </p><ul class="list-bullet">
  1000. <li class="item"><p class="para">
  1001. There <em>isn’t</em> a value at all
  1002. </p>
  1003. </li>
  1004. </ul><div class="note">
  1005. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_497"></a>
  1006. <aside class="aside">
  1007. <p class="aside-title">Note
  1008. </p>
  1009. <p class="para">The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return <code class="code-voice">nil</code> from a method that would otherwise return an object, with <code class="code-voice">nil</code> meaning “the absence of a valid object.” However, this only works for objects—it doesn’t work for structures, basic C types, or enumeration values. For these types, Objective-C methods typically return a special value (such as <code class="code-voice">NSNotFound</code>) to indicate the absence of a value. This approach assumes that the method’s caller knows there is a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for <em>any type at all</em>, without the need for special constants.
  1010. </p>
  1011.  
  1012. </aside>
  1013. </div><p class="para">
  1014. Here’s an example of how optionals can be used to cope with the absence of a value. Swift’s <code class="code-voice">String</code> type has a method called <code class="code-voice">toInt</code>, which tries to convert a <code class="code-voice">String</code> value into an <code class="code-voice">Int</code> value. However, not every string can be converted into an integer. The string <code class="code-voice">&quot;123&quot;</code> can be converted into the numeric value <code class="code-voice">123</code>, but the string <code class="code-voice">&quot;hello, world&quot;</code> does not have an obvious numeric value to convert to.
  1015. </p><p class="para">
  1016. The example below uses the <code class="code-voice">toInt</code> method to try to convert a <code class="code-voice">String</code> into an <code class="code-voice">Int</code>:
  1017. </p><section class="code-listing">
  1018.  
  1019. <span class="caption"></span>
  1020. <div class="code-sample">
  1021.  
  1022. <ul class="code-lines">
  1023. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">possibleNumber</span> = <span class="s">&quot;123&quot;</span></code></li>
  1024. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">convertedNumber</span> = <span class="vc">possibleNumber</span>.<span class="vc">toInt</span>()</code></li>
  1025. <li><code class="code-voice"><span class="c">// convertedNumber is inferred to be of type &quot;Int?&quot;, or &quot;optional Int&quot;</span></code></li>
  1026. </ul>
  1027.  
  1028.  
  1029.  
  1030. </div>
  1031. </section><p class="para">
  1032. Because the <code class="code-voice">toInt</code> method might fail, it returns an <em>optional</em> <code class="code-voice">Int</code>, rather than an <code class="code-voice">Int</code>. An optional <code class="code-voice">Int</code> is written as <code class="code-voice">Int?</code>, not <code class="code-voice">Int</code>. The question mark indicates that the value it contains is optional, meaning that it might contain <em>some</em> <code class="code-voice">Int</code> value, or it might contain <em>no value at all</em>. (It can’t contain anything else, such as a <code class="code-voice">Bool</code> value or a <code class="code-voice">String</code> value. It’s either an <code class="code-voice">Int</code>, or it’s nothing at all.)
  1033. </p>
  1034. <section class="section">
  1035. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_498"></a>
  1036. <h3 class="section-name" tabindex="0">nil</h3>
  1037. <p class="para">
  1038. You set an optional variable to a valueless state by assigning it the special value <code class="code-voice">nil</code>:
  1039. </p><section class="code-listing">
  1040.  
  1041. <span class="caption"></span>
  1042. <div class="code-sample">
  1043.  
  1044. <ul class="code-lines">
  1045. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">serverResponseCode</span>: <span class="n"><!-- a href="" -->Int<!-- /a --></span>? = <span class="m">404</span></code></li>
  1046. <li><code class="code-voice"><span class="c">// serverResponseCode contains an actual Int value of 404</span></code></li>
  1047. <li><code class="code-voice"><span class="vc">serverResponseCode</span> = <span class="kt">nil</span></code></li>
  1048. <li><code class="code-voice"><span class="c">// serverResponseCode now contains no value</span></code></li>
  1049. </ul>
  1050.  
  1051.  
  1052.  
  1053. </div>
  1054. </section><div class="note">
  1055. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_499"></a>
  1056. <aside class="aside">
  1057. <p class="aside-title">Note
  1058. </p>
  1059. <p class="para"><code class="code-voice">nil</code> cannot be used with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.
  1060. </p>
  1061.  
  1062. </aside>
  1063. </div><p class="para">
  1064. If you define an optional constant or variable without providing a default value, the constant or variable is automatically set to <code class="code-voice">nil</code> for you:
  1065. </p><section class="code-listing">
  1066.  
  1067. <span class="caption"></span>
  1068. <div class="code-sample">
  1069.  
  1070. <ul class="code-lines">
  1071. <li><code class="code-voice"><span class="kt">var</span> <span class="vc">surveyAnswer</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span>?</code></li>
  1072. <li><code class="code-voice"><span class="c">// surveyAnswer is automatically set to nil</span></code></li>
  1073. </ul>
  1074.  
  1075.  
  1076.  
  1077. </div>
  1078. </section><div class="note">
  1079. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_500"></a>
  1080. <aside class="aside">
  1081. <p class="aside-title">Note
  1082. </p>
  1083. <p class="para">Swift’s <code class="code-voice">nil</code> is not the same as <code class="code-voice">nil</code> in Objective-C. In Objective-C, <code class="code-voice">nil</code> is a pointer to a nonexistent object. In Swift, <code class="code-voice">nil</code> is not a pointer—it is the absence of a value of a certain type. Optionals of <em>any</em> type can be set to <code class="code-voice">nil</code>, not just object types.
  1084. </p>
  1085.  
  1086. </aside>
  1087. </div>
  1088.  
  1089. </section>
  1090. <section class="section">
  1091. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_501"></a>
  1092. <h3 class="section-name" tabindex="0">If Statements and Forced Unwrapping</h3>
  1093. <p class="para">
  1094. You can use an <code class="code-voice">if</code> statement to find out whether an optional contains a value by comparing the optional against <code class="code-voice">nil</code>. You perform this comparison with the “equal to” operator (<code class="code-voice">==</code>) or the “not equal to” operator (<code class="code-voice">!=</code>).
  1095. </p><p class="para">
  1096. If an optional has a value, it is considered to be “not equal to” <code class="code-voice">nil</code>:
  1097. </p><section class="code-listing">
  1098.  
  1099. <span class="caption"></span>
  1100. <div class="code-sample">
  1101.  
  1102. <ul class="code-lines">
  1103. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">convertedNumber</span> != <span class="kt">nil</span> {</code></li>
  1104. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;convertedNumber contains some integer value.&quot;</span>)</code></li>
  1105. <li><code class="code-voice">}</code></li>
  1106. <li><code class="code-voice"><span class="c">// prints &quot;convertedNumber contains some integer value.&quot;</span></code></li>
  1107. </ul>
  1108.  
  1109.  
  1110.  
  1111. </div>
  1112. </section><p class="para">
  1113. Once you’re sure that the optional <em>does</em> contain a value, you can access its underlying value by adding an exclamation mark (<code class="code-voice">!</code>) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as <em>forced unwrapping</em> of the optional’s value:
  1114. </p><section class="code-listing">
  1115.  
  1116. <span class="caption"></span>
  1117. <div class="code-sample">
  1118.  
  1119. <ul class="code-lines">
  1120. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">convertedNumber</span> != <span class="kt">nil</span> {</code></li>
  1121. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;convertedNumber has an integer value of </span>\(<span class="vc">convertedNumber</span>!)<span class="s">.&quot;</span>)</code></li>
  1122. <li><code class="code-voice">}</code></li>
  1123. <li><code class="code-voice"><span class="c">// prints &quot;convertedNumber has an integer value of 123.&quot;</span></code></li>
  1124. </ul>
  1125.  
  1126.  
  1127.  
  1128. </div>
  1129. </section><p class="para">
  1130. For more on the <code class="code-voice">if</code> statement, see <span class="x-name"><a href="ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_190" data-id="//apple_ref/doc/uid/TP40014097-CH9-XID_190">Control Flow</a></span>.
  1131. </p><div class="note">
  1132. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_502"></a>
  1133. <aside class="aside">
  1134. <p class="aside-title">Note
  1135. </p>
  1136. <p class="para">Trying to use <code class="code-voice">!</code> to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-<code class="code-voice">nil</code> value before using <code class="code-voice">!</code> to force-unwrap its value.
  1137. </p>
  1138.  
  1139. </aside>
  1140. </div>
  1141.  
  1142. </section>
  1143. <section class="section">
  1144. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_503"></a>
  1145. <h3 class="section-name" tabindex="0">Optional Binding</h3>
  1146. <p class="para">
  1147. You use <em>optional binding</em> to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with <code class="code-voice">if</code> and <code class="code-voice">while</code> statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action. <code class="code-voice">if</code> and <code class="code-voice">while</code> statements are described in more detail in <span class="x-name"><a href="ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_190" data-id="//apple_ref/doc/uid/TP40014097-CH9-XID_190">Control Flow</a></span>.
  1148. </p><p class="para">
  1149. Write optional bindings for the <code class="code-voice">if</code> statement as follows:
  1150. </p><span class="caption"></span>
  1151. <div class="code-outline">
  1152. <ul class="code-outline-lines">
  1153. <li><pre class="code-voice"><span class="kt">if</span> <span class="kt">let</span> <em class="variable-text">constantName</em> = <em class="variable-text">someOptional</em> {</pre></li><li><pre class="code-voice"> <em class="variable-text">statements</em></pre></li><li><pre class="code-voice">}</pre></li>
  1154. </ul>
  1155. </div><p class="para">
  1156. You can rewrite the <code class="code-voice">possibleNumber</code> example from the <span class="x-name"><a href="#//apple_ref/doc/uid/TP40014097-CH5-XID_496" data-id="//apple_ref/doc/uid/TP40014097-CH5-XID_496">Optionals</a></span> section to use optional binding rather than forced unwrapping:
  1157. </p><section class="code-listing">
  1158.  
  1159. <span class="caption"></span>
  1160. <div class="code-sample">
  1161.  
  1162. <ul class="code-lines">
  1163. <li><code class="code-voice"><span class="kt">if</span> <span class="kt">let</span> <span class="vc">actualNumber</span> = <span class="vc">possibleNumber</span>.<span class="vc">toInt</span>() {</code></li>
  1164. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;\&#39;</span>\(<span class="vc">possibleNumber</span>)<span class="s">\&#39; has an integer value of </span>\(<span class="vc">actualNumber</span>)<span class="s">&quot;</span>)</code></li>
  1165. <li><code class="code-voice">} <span class="kt">else</span> {</code></li>
  1166. <li><code class="code-voice"> <span class="vc">println</span>(<span class="s">&quot;\&#39;</span>\(<span class="vc">possibleNumber</span>)<span class="s">\&#39; could not be converted to an integer&quot;</span>)</code></li>
  1167. <li><code class="code-voice">}</code></li>
  1168. <li><code class="code-voice"><span class="c">// prints &quot;&#39;123&#39; has an integer value of 123&quot;</span></code></li>
  1169. </ul>
  1170.  
  1171.  
  1172.  
  1173. </div>
  1174. </section><p class="para">
  1175. This code can be read as:
  1176. </p><p class="para">
  1177. “If the optional <code class="code-voice">Int</code> returned by <code class="code-voice">possibleNumber.toInt</code> contains a value, set a new constant called <code class="code-voice">actualNumber</code> to the value contained in the optional.”
  1178. </p><p class="para">
  1179. If the conversion is successful, the <code class="code-voice">actualNumber</code> constant becomes available for use within the first branch of the <code class="code-voice">if</code> statement. It has already been initialized with the value contained <em>within</em> the optional, and so there is no need to use the <code class="code-voice">!</code> suffix to access its value. In this example, <code class="code-voice">actualNumber</code> is simply used to print the result of the conversion.
  1180. </p><p class="para">
  1181. You can use both constants and variables with optional binding. If you wanted to manipulate the value of <code class="code-voice">actualNumber</code> within the first branch of the <code class="code-voice">if</code> statement, you could write <code class="code-voice">if var actualNumber</code> instead, and the value contained within the optional would be made available as a variable rather than a constant.
  1182. </p>
  1183.  
  1184. </section>
  1185. <section class="section">
  1186. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_504"></a>
  1187. <h3 class="section-name" tabindex="0">Implicitly Unwrapped Optionals</h3>
  1188. <p class="para">
  1189. As described above, optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an <code class="code-voice">if</code> statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist.
  1190. </p><p class="para">
  1191. Sometimes it is clear from a program’s structure that an optional will <em>always</em> have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.
  1192. </p><p class="para">
  1193. These kinds of optionals are defined as <em>implicitly unwrapped optionals</em>. You write an implicitly unwrapped optional by placing an exclamation mark (<code class="code-voice">String!</code>) rather than a question mark (<code class="code-voice">String?</code>) after the type that you want to make optional.
  1194. </p><p class="para">
  1195. Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in <span class="x-name"><a href="AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_98" data-id="//apple_ref/doc/uid/TP40014097-CH20-XID_98">Unowned References and Implicitly Unwrapped Optional Properties</a></span>.
  1196. </p><p class="para">
  1197. An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed. The following example shows the difference in behavior between an optional string and an implicitly unwrapped optional string when accessing their wrapped value as an explicit <code class="code-voice">String</code>:
  1198. </p><section class="code-listing">
  1199.  
  1200. <span class="caption"></span>
  1201. <div class="code-sample">
  1202.  
  1203. <ul class="code-lines">
  1204. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">possibleString</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span>? = <span class="s">&quot;An optional string.&quot;</span></code></li>
  1205. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">forcedString</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span> = <span class="vc">possibleString</span>! <span class="c">// requires an exclamation mark</span></code></li>
  1206. <li><code class="code-voice"> </code></li>
  1207. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">assumedString</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span>! = <span class="s">&quot;An implicitly unwrapped optional string.&quot;</span></code></li>
  1208. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">implicitString</span>: <span class="n"><!-- a href="" -->String<!-- /a --></span> = <span class="vc">assumedString</span> <span class="c">// no need for an exclamation mark</span></code></li>
  1209. </ul>
  1210.  
  1211.  
  1212.  
  1213. </div>
  1214. </section><p class="para">
  1215. You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an exclamation mark after the optional’s type when you declare it.
  1216. </p><div class="note">
  1217. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_505"></a>
  1218. <aside class="aside">
  1219. <p class="aside-title">Note
  1220. </p>
  1221. <p class="para">If you try to access an implicitly unwrapped optional when it does not contain a value, you will trigger a runtime error. The result is exactly the same as if you place an exclamation mark after a normal optional that does not contain a value.
  1222. </p>
  1223.  
  1224. </aside>
  1225. </div><p class="para">
  1226. You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:
  1227. </p><section class="code-listing">
  1228.  
  1229. <span class="caption"></span>
  1230. <div class="code-sample">
  1231.  
  1232. <ul class="code-lines">
  1233. <li><code class="code-voice"><span class="kt">if</span> <span class="vc">assumedString</span> != <span class="kt">nil</span> {</code></li>
  1234. <li><code class="code-voice"> <span class="vc">println</span>(<span class="vc">assumedString</span>)</code></li>
  1235. <li><code class="code-voice">}</code></li>
  1236. <li><code class="code-voice"><span class="c">// prints &quot;An implicitly unwrapped optional string.&quot;</span></code></li>
  1237. </ul>
  1238.  
  1239.  
  1240.  
  1241. </div>
  1242. </section><p class="para">
  1243. You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement:
  1244. </p><section class="code-listing">
  1245.  
  1246. <span class="caption"></span>
  1247. <div class="code-sample">
  1248.  
  1249. <ul class="code-lines">
  1250. <li><code class="code-voice"><span class="kt">if</span> <span class="kt">let</span> <span class="vc">definiteString</span> = <span class="vc">assumedString</span> {</code></li>
  1251. <li><code class="code-voice"> <span class="vc">println</span>(<span class="vc">definiteString</span>)</code></li>
  1252. <li><code class="code-voice">}</code></li>
  1253. <li><code class="code-voice"><span class="c">// prints &quot;An implicitly unwrapped optional string.&quot;</span></code></li>
  1254. </ul>
  1255.  
  1256.  
  1257.  
  1258. </div>
  1259. </section><div class="note">
  1260. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_506"></a>
  1261. <aside class="aside">
  1262. <p class="aside-title">Note
  1263. </p>
  1264. <p class="para">Do not use an implicitly unwrapped optional when there is a possibility of a variable becoming <code class="code-voice">nil</code> at a later point. Always use a normal optional type if you need to check for a <code class="code-voice">nil</code> value during the lifetime of a variable.
  1265. </p>
  1266.  
  1267. </aside>
  1268. </div>
  1269.  
  1270. </section>
  1271.  
  1272. </section>
  1273. <section class="section">
  1274. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_507"></a>
  1275. <h3 class="section-name" tabindex="0">Assertions</h3>
  1276. <p class="para">
  1277. Optionals enable you to check for values that may or may not exist, and to write code that copes gracefully with the absence of a value. In some cases, however, it is simply not possible for your code to continue execution if a value does not exist, or if a provided value does not satisfy certain conditions. In these situations, you can trigger an <em>assertion</em> in your code to end code execution and to provide an opportunity to debug the cause of the absent or invalid value.
  1278. </p>
  1279. <section class="section">
  1280. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_508"></a>
  1281. <h3 class="section-name" tabindex="0">Debugging with Assertions</h3>
  1282. <p class="para">
  1283. An assertion is a runtime check that a logical condition definitely evaluates to <code class="code-voice">true</code>. Literally put, an assertion “asserts” that a condition is true. You use an assertion to make sure that an essential condition is satisfied before executing any further code. If the condition evaluates to <code class="code-voice">true</code>, code execution continues as usual; if the condition evaluates to <code class="code-voice">false</code>, code execution ends, and your app is terminated.
  1284. </p><p class="para">
  1285. If your code triggers an assertion while running in a debug environment, such as when you build and run an app in Xcode, you can see exactly where the invalid state occurred and query the state of your app at the time that the assertion was triggered. An assertion also lets you provide a suitable debug message as to the nature of the assert.
  1286. </p><p class="para">
  1287. You write an assertion by calling the global <code class="code-voice">assert</code> function. You pass the <code class="code-voice">assert</code> function an expression that evaluates to <code class="code-voice">true</code> or <code class="code-voice">false</code> and a message that should be displayed if the result of the condition is <code class="code-voice">false</code>:
  1288. </p><section class="code-listing">
  1289.  
  1290. <span class="caption"></span>
  1291. <div class="code-sample">
  1292.  
  1293. <ul class="code-lines">
  1294. <li><code class="code-voice"><span class="kt">let</span> <span class="vc">age</span> = -<span class="m">3</span></code></li>
  1295. <li><code class="code-voice"><span class="vc">assert</span>(<span class="vc">age</span> &gt;= <span class="m">0</span>, <span class="s">&quot;A person&#39;s age cannot be less than zero&quot;</span>)</code></li>
  1296. <li><code class="code-voice"><span class="c">// this causes the assertion to trigger, because age is not &gt;= 0</span></code></li>
  1297. </ul>
  1298.  
  1299.  
  1300.  
  1301. </div>
  1302. </section><p class="para">
  1303. In this example, code execution will continue only if <code class="code-voice">age &gt;= 0</code> evaluates to <code class="code-voice">true</code>, that is, if the value of <code class="code-voice">age</code> is non-negative. If the value of <code class="code-voice">age</code> <em>is</em> negative, as in the code above, then <code class="code-voice">age &gt;= 0</code> evaluates to <code class="code-voice">false</code>, and the assertion is triggered, terminating the application.
  1304. </p><p class="para">
  1305. The assertion message can be omitted if desired, as in the following example:
  1306. </p><section class="code-listing">
  1307.  
  1308. <span class="caption"></span>
  1309. <div class="code-sample">
  1310.  
  1311. <ul class="code-lines">
  1312. <li><code class="code-voice"><span class="vc">assert</span>(<span class="vc">age</span> &gt;= <span class="m">0</span>)</code></li>
  1313. </ul>
  1314.  
  1315.  
  1316.  
  1317. </div>
  1318. </section>
  1319.  
  1320. </section>
  1321. <section class="section">
  1322. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_509"></a>
  1323. <h3 class="section-name" tabindex="0">When to Use Assertions</h3>
  1324. <p class="para">
  1325. Use an assertion whenever a condition has the potential to be false, but must <em>definitely</em> be true in order for your code to continue execution. Suitable scenarios for an assertion check include:
  1326. </p><ul class="list-bullet">
  1327. <li class="item"><p class="para">
  1328. An integer subscript index is passed to a custom subscript implementation, but the subscript index value could be too low or too high.
  1329. </p>
  1330. </li><li class="item"><p class="para">
  1331. A value is passed to a function, but an invalid value means that the function cannot fulfill its task.
  1332. </p>
  1333. </li><li class="item"><p class="para">
  1334. An optional value is currently <code class="code-voice">nil</code>, but a non-<code class="code-voice">nil</code> value is essential for subsequent code to execute successfully.
  1335. </p>
  1336. </li>
  1337. </ul><p class="para">
  1338. See also <span class="x-name"><a href="Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-XID_461" data-id="//apple_ref/doc/uid/TP40014097-CH16-XID_461">Subscripts</a></span> and <span class="x-name"><a href="Functions.html#//apple_ref/doc/uid/TP40014097-CH10-XID_243" data-id="//apple_ref/doc/uid/TP40014097-CH10-XID_243">Functions</a></span>.
  1339. </p><div class="note">
  1340. <a name="//apple_ref/doc/uid/TP40014097-CH5-XID_510"></a>
  1341. <aside class="aside">
  1342. <p class="aside-title">Note
  1343. </p>
  1344. <p class="para">Assertions cause your app to terminate and are not a substitute for designing your code in such a way that invalid conditions are unlikely to arise. Nonetheless, in situations where invalid conditions are possible, an assertion is an effective way to ensure that such conditions are highlighted and noticed during development, before your app is published.
  1345. </p>
  1346.  
  1347. </aside>
  1348. </div>
  1349.  
  1350. </section>
  1351.  
  1352. </section>
  1353.  
  1354.  
  1355. <section id="next_previous" class="">
  1356. <p class="copyright">Copyright &#x00a9; 2014 Apple Inc. All rights reserved. <a class="link" href="http://www.apple.com/legal/terms/site.html" target="_blank" rel='external'>Terms of Use</a> | <a class="link" href="http://www.apple.com/privacy/" target="_blank" rel='external'>Privacy Policy</a> | true
  1357. </p>
  1358. </section>
  1359. </article>
  1360. </body>
  1361. </html>
Advertisement
Add Comment
Please, Sign In to add comment