Files
the-swift-programming-langu…/chapter2/01_The_Basics.html
2014-06-06 18:32:09 +08:00

823 lines
43 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>基础部分 | Swift 编程语言</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/02_Basic_Operators.html" />
<link rel="prev" href="../chapter2/chapter2.html" />
<meta property="og:title" content="基础部分 | Swift 编程语言">
<meta property="og:site_name" content="Swift 编程语言">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.1" data-basepath=".." data-revision="1402050704574">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >Swift 编程语言</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i> Introduction</a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
<a href="../chapter1/chapter1.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
<a href="../chapter1/01_swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
<a href="../chapter1/02_a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
<a href="../chapter2/chapter2.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
<a href="../chapter2/01_The_Basics.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
<a href="../chapter2/02_Basic_Operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
<a href="../chapter2/03_Strings_and_Characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
<li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
<a href="../chapter2/04_Collection_Types.html">
<i class="fa fa-check"></i> <b>2.4.</b> 集合类型
</a>
</li>
<li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
<a href="../chapter2/05_Control_Flow.html">
<i class="fa fa-check"></i> <b>2.5.</b> 控制流
</a>
</li>
<li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
<a href="../chapter2/06_Functions.html">
<i class="fa fa-check"></i> <b>2.6.</b> 函数
</a>
</li>
<li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
<a href="../chapter2/07_Closures.html">
<i class="fa fa-check"></i> <b>2.7.</b> 闭包
</a>
</li>
<li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
<a href="../chapter2/08_Enumerations.html">
<i class="fa fa-check"></i> <b>2.8.</b> 枚举
</a>
</li>
<li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
<a href="../chapter2/09_Classes_and_Structures.html">
<i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
</a>
</li>
<li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
<a href="../chapter2/10_Properties.html">
<i class="fa fa-check"></i> <b>2.10.</b> 属性
</a>
</li>
<li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
<a href="../chapter2/11_Methods.html">
<i class="fa fa-check"></i> <b>2.11.</b> 方法
</a>
</li>
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
<a href="../chapter2/12_Subscripts.html">
<i class="fa fa-check"></i> <b>2.12.</b> 下标
</a>
</li>
<li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
<a href="../chapter2/13_Inheritance.html">
<i class="fa fa-check"></i> <b>2.13.</b> 继承
</a>
</li>
<li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
<a href="../chapter2/14_Initialization.html">
<i class="fa fa-check"></i> <b>2.14.</b> 构造函数
</a>
</li>
<li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
<a href="../chapter2/15_Deinitialization.html">
<i class="fa fa-check"></i> <b>2.15.</b> 析构函数
</a>
</li>
<li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
<a href="../chapter2/16_Automatic_Reference_Counting.html">
<i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
</a>
</li>
<li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
<a href="../chapter2/17_Optional_Chaining.html">
<i class="fa fa-check"></i> <b>2.17.</b> 可选链
</a>
</li>
<li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
<a href="../chapter2/18_Type_Casting.html">
<i class="fa fa-check"></i> <b>2.18.</b> 类型检查
</a>
</li>
<li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
<a href="../chapter2/19_Nested_Types.html">
<i class="fa fa-check"></i> <b>2.19.</b> 嵌套类型
</a>
</li>
<li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
<a href="../chapter2/20_Extensions.html">
<i class="fa fa-check"></i> <b>2.20.</b> 扩展
</a>
</li>
<li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
<a href="../chapter2/21_Protocols.html">
<i class="fa fa-check"></i> <b>2.21.</b> 接口
</a>
</li>
<li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
<a href="../chapter2/22_Generics.html">
<i class="fa fa-check"></i> <b>2.22.</b> 泛型
</a>
</li>
<li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
<a href="../chapter2/23_Advanced_Operators.html">
<i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
<a href="../chapter3/chapter3.html">
<i class="fa fa-check"></i> <b>3.</b> 语言参考
</a>
<ul class="articles">
<li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
<a href="../chapter3/01_About_the_Language_Reference.html">
<i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
</a>
</li>
<li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
<a href="../chapter3/02_Lexical_Structure.html">
<i class="fa fa-check"></i> <b>3.2.</b> 词法结构
</a>
</li>
<li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
<a href="../chapter3/03_Types.html">
<i class="fa fa-check"></i> <b>3.3.</b> 类型
</a>
</li>
<li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
<a href="../chapter3/04_Expressions.html">
<i class="fa fa-check"></i> <b>3.4.</b> 表达式
</a>
</li>
<li class="chapter " data-level="3.5" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.5.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.6.</b> 属性
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.7.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
<i class="fa fa-check"></i> <b>3.8.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.9" data-path="chapter3/09_Summary_of_the_Grammar.html">
<a href="../chapter3/09_Summary_of_the_Grammar.html">
<i class="fa fa-check"></i> <b>3.9.</b> 语法总结
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 13.513513513513514%;min-width: 10.81081081081081%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.7027027027027026%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.405405405405405%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 8.108108108108109%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.81081081081081%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.513513513513514%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter " data-progress="2.10" style="left: 16.216216216216218%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter " data-progress="2.11" style="left: 18.91891891891892%;"></a>
<a href="../chapter2/12_Subscripts.html" title="下标" class="chapter " data-progress="2.12" style="left: 21.62162162162162%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter " data-progress="2.13" style="left: 24.324324324324323%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造函数" class="chapter " data-progress="2.14" style="left: 27.027027027027028%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构函数" class="chapter " data-progress="2.15" style="left: 29.72972972972973%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter " data-progress="2.16" style="left: 32.432432432432435%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter " data-progress="2.17" style="left: 35.13513513513514%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter " data-progress="2.18" style="left: 37.83783783783784%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="嵌套类型" class="chapter " data-progress="2.19" style="left: 40.54054054054054%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 43.24324324324324%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter " data-progress="2.20" style="left: 45.945945945945944%;"></a>
<a href="../chapter2/21_Protocols.html" title="接口" class="chapter " data-progress="2.21" style="left: 48.648648648648646%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter " data-progress="2.22" style="left: 51.351351351351354%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter " data-progress="2.23" style="left: 54.054054054054056%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 56.75675675675676%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter " data-progress="2.4" style="left: 59.45945945945946%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter " data-progress="2.5" style="left: 62.16216216216216%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter " data-progress="2.6" style="left: 64.86486486486487%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " data-progress="2.7" style="left: 67.56756756756756%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter " data-progress="2.8" style="left: 70.27027027027027%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter " data-progress="2.9" style="left: 72.97297297297297%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter new-chapter" data-progress="3" style="left: 75.67567567567568%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter " data-progress="3.1" style="left: 78.37837837837837%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter " data-progress="3.2" style="left: 81.08108108108108%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter " data-progress="3.3" style="left: 83.78378378378379%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.48648648648648%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.5" style="left: 89.1891891891892%;"></a>
<a href="../chapter3/06_Attributes.html" title="属性" class="chapter " data-progress="3.6" style="left: 91.89189189189189%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.7" style="left: 94.5945945945946%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.8" style="left: 97.29729729729729%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_12">
<h1 id="-">基础部分</h1>
<p>Swift 是 iOS 和 OS X 应用开发的一门新语言。然而,如果你有 C 或者 Objective-C 开发经验的话,你会发现 Swift 的很多内容都是你熟悉的。</p>
<p>Swift 的类型是在 C 和 Objective-C 的基础上提出的,<code>Int</code>是整型;<code>Double</code><code>Float</code>是浮点型;<code>Bool</code>是布尔型;<code>String</code>是字符串。Swift 还有两个有用的集合类型,<code>Array</code><code>Dictionary</code>,详情参见<code>集合类型(待添加链接)</code></p>
<p>就像 C 语言一样Swift 使用变量来进行存储并通过变量名来关联值。在 Swift 中,值不可变的变量有着广泛的应用,它们就是常量,而且比 C 语言的常量更强大。在 Swift 中,如果你要处理的值不需要改变,那使用常量可以让你的代码更加安全并且更好地表达你的意图。</p>
<p>除了我们熟悉的类型Swift 还增加了 Objective-C 中没有的类型比如元组Tuple。元组可以让你创建或者传递一组数据比如作为函数的返回值时你可以用一个元组可以返回多个值。</p>
<p>Swift 还增加了可选Optional类型用于处理值缺失的情况。可选表示“那儿有一个值并且它等于 x ”或者“那儿没有值”。可选有点像在 Objective-C 中使用<code>nil</code>,但是它可以用在任何类型上,不仅仅是类。可选类型比 Objective-C 中的<code>nil</code>指针更加安全也更具表现力,它是 Swift 许多强大特性的重要组成部分。</p>
<p>Swift 是一个类型安全的语言可选就是一个很好的例子。Swift 可以让你清楚地知道值的类型。如果你的代码期望得到一个<code>String</code>,类型安全会阻止你不小心传入一个<code>Int</code>。你可以在开发阶段尽早发现并修正错误。</p>
<h2 id="-">常量和变量</h2>
<p>常量和变量把一个名字(比如<code>maximumNumberOfLoginAttempts</code>或者<code>welcomeMessage</code>)和一个指定类型的值(比如数字<code>10</code>或者字符串<code>Hello</code>)关联起来。常量的值一旦设定就不能改变,而变量的值可以随意更改。</p>
<h3 id="-">声明常量和变量</h3>
<p>常量和变量必须在使用前声明,用<code>let</code>来声明常量,用<code>var</code>来声明变量。下面的例子展示了如何用常量和变量来记录用户尝试登录的次数:</p>
<pre><code>let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
</code></pre><p>这两行代码可以被理解为
“声明一个名字是<code>maximumNumberOfLoginAttempts</code>的新常量,并给它一个值<code>10</code>。然后,声明一个名字是<code>currentLoginAttempt</code>的变量并将它的值初始化为0.”</p>
<p>在这个例子中,允许的最大尝试登录次数被声明为一个常量,因为这个值不会改变。当前尝试登录次数被声明为一个变量,因为每次尝试登录失败的时候都需要增加这个值。</p>
<p>你可以在一行中声明多个常量或者多个变量,用逗号隔开:</p>
<pre><code>var x = 0.0, y = 0.0, z = 0.0
</code></pre><blockquote>
<p>注意:如果你的代码中有不需要改变的值,请将它声明为常量。只将需要改变的值声明为变量。</p>
</blockquote>
<h3 id="-">类型标注</h3>
<p>当你声明常量或者变量的时候可以加上类型标注,说明常量或者变量中要存储的值的类型。如果要添加类型标注,在常量或者变量名后面加上一个冒号和空格,然后加上类型名称。</p>
<p>这个例子给<code>welcomeMessage</code>变量添加了类型标注,表示这个变量可以存储<code>String</code>类型的值:</p>
<pre><code>var welcomeMessage: String
</code></pre><p>声明中的冒号代表着“是...类型”,所以这行代码可以被理解为::</p>
<p>“声明一个类型为<code>String</code>,名字为<code>welcomeMessage</code>的变量。”</p>
<p>“类型为<code>String</code>”的意思是“可以存储任意<code>String</code>类型的值。”</p>
<p><code>welcomeMessage</code>变量现在可以被设置成任意字符串:</p>
<pre><code>welcomeMessage = &quot;Hello&quot;
</code></pre><blockquote>
<p>注意一般来说你很少需要写类型标注。如果你在声明常量或者变量的时候赋了一个初始值Swift可以推断出这个常量或者变量的类型详情参见<code>类型安全和类型推断(待添加链接)</code>。在上面的例子中,没有给<code>welcomeMessage</code>赋初始值,所以添加了一个类型标注。</p>
</blockquote>
<h3 id="-">常量和变量的命名</h3>
<p>你可以用任何你喜欢的字符作为常量和变量名包括Unicode字符</p>
<pre><code> let π = 3.14159
let 你好 = &quot;你好世界&quot;
let 🐶🐮 = &quot;dogcow&quot;
</code></pre><p>常量与变量名不能包含数学符号,箭头,保留的(或者非法的)Unicode码位连线与制表符。尽管常量与变量名中可以包含数字但是它们不能以数字打头。</p>
<p>一旦你将常量或者变量声明为确定的类型,你就不能使用相同的名字再次进行声明,或者以改变其存储的值为其他类型。同时,你也不能将常量与变量进行互转。</p>
<blockquote>
<p>注意如果你需要使用与Swift保留关键字相同的名称作为常量或者变量名你可以使用反引号(`)将关键字围住的方式将其作为名字使用。无论如何,你应当避免使用关键字作为常量或变量名,除非你别无选择。</p>
</blockquote>
<p>你可以更改现有的变量值为其他同类型的值,在下面的例子中,<code>friendlyWelcome</code>的值从<code>&quot;Hello!&quot;</code>改为了<code>&quot;Bonjour!&quot;</code>:</p>
<pre><code> var friendlyWelcome = &quot;Hello!&quot;
friendlyWelcome = &quot;Bonjour!&quot;
// friendlyWelcome is now &quot;Bonjour!&quot;
</code></pre><p>和变量不一样,常量的值一旦被确定以后就不能更改了。尝试这样做会在编译时报错:</p>
<pre><code> let languageName = &quot;Swift&quot;
languageName = &quot;Swift++&quot;
// this is a compile-time error - languageName cannot be changed
</code></pre><h3 id="-">输出常量和变量</h3>
<p>你可以用<code>println</code>函数来输出当前常量或变量的值:</p>
<pre><code> println(friendlyWelcome)
// prints &quot;Bonjour!&quot;
</code></pre><p><code>println</code>是一个用来输出的全局函数输出的内容会在最后带换行。如果你用Xcode<code>println</code>将会输出内容到“console”面板上。(另一种函数叫<code>print</code>,唯一区别是在输出内容最后不会加入换行。)</p>
<p><code>println</code>函数输出传入的<code>String</code>值:</p>
<pre><code> println(&quot;This is a string&quot;)
// prints &quot;This is a string&quot;
</code></pre><p>像Cocoa里的<code>NSLog</code>函数一样,<code>println</code>函数可以输出更复杂的信息。这些信息可以包含当前常量和变量的值。</p>
<p>Swift用字符串插值string interpolation的方式把常量名或者变量名当做占位符加入到长字符串中Swift会用当前常量或变量的值替换这些占位符。将常量或变量名放入反斜杠符加一对圆括号中<code>&quot;\()&quot;</code></p>
<pre><code> println(&quot;The current value of friendlyWelcome is \(friendlyWelcome)&quot;)
// prints &quot;The current value of friendlyWelcome is Bonjour!
</code></pre><blockquote>
<p>注意:字符串插值所有可用的选项在 字符串插值 这章中讲述。</p>
</blockquote>
<h3 id="-">注释</h3>
<p>请将你的代码中的非执行文本注释成提示或者笔记以方便你将来阅读。Swift 的编译器将会在编译代码时自动忽略掉注释部分。</p>
<p>Swift 中的注释与C 语言的注释非常相似。单行注释以双正斜杠作(//)为起始标记:</p>
<pre><code>// this is a comment
</code></pre><p>你也可以进行多行注释,其起始标记为单个正斜杠后跟随一个星号(/*),终止标记为一个星号后跟随单个正斜杠(*/):</p>
<pre><code>/* this is also a comment,
but written over multiple lines */
</code></pre><p>与C 语言多行注释不同的是Swift 的多行注释可以嵌套在其它的多行注释之中。你可以先生成一个多行注释块,然后在这个注释块之中再嵌套成第二个多行注释。终止注释时先插入第二个注释块的终止标记,然后再插入第一个注释块的终止标记:</p>
<pre><code>/* this is the start of the first multiline comment
/* this is the second, nested multiline comment */
this is the end of the first multiline comment */
</code></pre><p>通过运用嵌套多行注释,你可以快速方便的注释掉一大段代码,即使这段代码之中已经含有了多行注释块。</p>
<h2 id="-">分号</h2>
<p>与其他大部分编程语言不同Swift 并不强制要求你在每条语句的结尾处使用分号(;),当然,你也可以按照你自己的习惯添加分号。有一种情况下必须要用分号,即你打算在同一行内写多条独立的语句:</p>
<pre><code>let cat = &quot;🐱&quot;; println(cat)
// prints &quot;🐱&quot;
</code></pre><h2 id="-">整数</h2>
<p>整数就是没有小数部分的数字,比如<code>42</code><code>-23</code>。整数可以是有符号(正、负、零)或者无符号(正、零)。</p>
<p>Swift 提供了8、16、32和64位的有符号和无符号整数类型。这些整数类型和 C 语言的命名方式很像比如8位无符号整数类型是<code>UInt8</code>32位有符号整数类型是<code>Int32</code>。就像 Swift 的其他类型一样,整数类型采用大写命名法。</p>
<h3 id="-">整数范围</h3>
<p>你可以访问不同整数类型的<code>min</code><code>max</code>属性来获取对应类型的最大值和最小值:</p>
<pre><code>let minValue = UInt8.min // minValue 为 0是 UInt8 类型的最小值
let maxValue = UInt8.max // maxValue 为 255是 UInt8 类型的最大值
</code></pre><h3 id="int">Int</h3>
<p>一般来说你不需要专门指定整数的长度。Swift 提供了一个特殊的整数类型<code>Int</code>,长度与当前平台的原生字长相同:</p>
<ul>
<li>在32位平台上<code>Int</code><code>Int32</code>长度相同。</li>
<li>在64位平台上<code>Int</code><code>Int64</code>长度相同。</li>
</ul>
<p>除非你需要特定长度的整数,一般来说使用<code>Int</code>就够了。这可以提高代码一致性和可复用性。即使是在32位平台上<code>Int</code>可以存储的整数范围也可以达到<code>-2147483648</code>~<code>2147483647</code>,大多数时候这已经足够大了。</p>
<h3 id="uint">UInt</h3>
<p>Swift 也提供了一个特殊的无符号类型<code>UInt</code>,长度与当前平台的原生字长相同:</p>
<ul>
<li>在32位平台上<code>UInt</code><code>UInt32</code>长度相同。</li>
<li>在64位平台上<code>UInt</code><code>UInt64</code>长度相同。</li>
</ul>
<blockquote>
<p>注意:尽量不要使用<code>UInt</code>,除非你真的需要存储一个和当前平台原生字长相同的无符号整数。除了这种情况,最好使用<code>Int</code>,即使你要存储的值已知是非负的。统一使用<code>Int</code>可以提高代码的可复用性,避免不同类型数字之间的转换,并且匹配数字的类型推测,详情参见<a href="## 类型安全和类型推测">类型安全和类型推测</a></p>
</blockquote>
<h2 id="-">浮点数</h2>
<p>浮点数是有小数部分的数字,比如<code>3.14159</code><code>0.1</code><code>-273.15</code></p>
<p>浮点类型比整数类型表示的范围更大,可以存储比<code>Int</code>类型更大或者更小的数字。Swift 提供了两种有符号浮点数类型:</p>
<ul>
<li><code>Double</code>表示64位浮点数。当你需要存储很大或者很高精度的浮点数时请使用此类型。</li>
<li><code>Float</code>表示32位浮点数。精度要求不高的话可以使用此类型。</li>
</ul>
<blockquote>
<p>注意:<code>Double</code>精确度很高至少有15位数字<code>Float</code>最少只有6位数字。选择哪个类型取决于你的代码需要处理的数字大小。</p>
</blockquote>
<h2 id="-">类型安全和类型推测</h2>
<p>Swift 是一个类型安全的语言。类型安全的语言可以让你清楚地知道代码要处理的值的类型。如果你的代码需要一个<code>String</code>,你绝对不可能不小心传进去一个<code>Int</code></p>
<p>Swift 是类型安全的,会在编译你的代码时进行类型检查,如果遇到不匹配的类型会报错。这可以让你在开发的时候尽早发现并修复错误。</p>
<p>当你要处理不同类型的值时类型检查可以帮你避免错误。然而这并不是说你每次声明常量和变量的时候都需要显式指定类型。如果你没有显式指定类型Swift 会使用类型推测来选择合适的类型。有了类型推测,编译器可以在编译代码的时候自动推测出表达式的类型。原理很简单,判断你赋的值即可。</p>
<p>因为有类型推测,和 C 或者 Objc 比起来 Swift 很少需要声明类型。常量和变量虽然需要明确类型,但是大部分工作并不需要你自己来完成。</p>
<p>当你声明常量或者变量并赋初值的时候类型推测非常有用。当你在声明常量或者变量的时候赋给它们一个原始值即可触发类型推测。(原始值就是会直接出现在你代码中的值,比如<code>42</code><code>3.14159</code>。)</p>
<p>举个例子,如果你给一个新常量赋值<code>42</code>并且没有标明类型Swift 可以推测出常量类型是<code>Int</code>,因为你给它赋的初值看起来很像一个整数:</p>
<pre><code>let meaningOfLife = 42
// meaningOfLife 会被推测为 Int 类型
</code></pre><p>同理如果你没有给浮点原始值标明类型Swift 会推测你想要的是<code>Double</code></p>
<pre><code>let pi = 3.14159
// pi 会被推测为 Double 类型
</code></pre><p>当推测浮点数的类型时Swift 总是会选择<code>Double</code>而不是<code>Float</code></p>
<p>如果表达式中同时出现了整数和浮点数,会被推测为<code>Double</code>类型:</p>
<pre><code>let anotherPi = 3 + 0.14159
// anotherPi 会被推测为 Double 类型
</code></pre><p>原始值<code>3</code>没有显式声明类型,而表达式中出现了一个浮点原始值,所以表达式会被推测为<code>Double</code>类型。</p>
<h2 id="-">数值类原始值</h2>
<p>整数原始值可以被写作:</p>
<ul>
<li>一个十进制数,没有前缀</li>
<li>一个二进制数,前缀是<code>0b</code></li>
<li>一个八进制数,前缀是<code>0o</code></li>
<li>一个十六进制数,前缀是<code>0x</code></li>
</ul>
<p>下面的所有整数原始值的十进制值都是<code>17</code>:</p>
<pre><code>let decimalInteger = 17
let binaryInteger = 0b10001 // 二进制的17
let octalInteger = 0o21 // 八进制的17
let hexadecimalInteger = 0x11 // 十六机制的17
</code></pre><p>浮点原始值可以是十进制(没有前缀)或者是十六进制(前缀是<code>0x</code>)。小数点两边必须有至少一个十进制数字(或者是十六进制的数字)。浮点原始值还有一个可选的指数,在十进制浮点数中通过大写或者小写的<code>e</code>来指定,在十六进制浮点数中通过大写或者小写的<code>p</code>来指定。</p>
<p>如果一个十进制数的指数为<code>exp</code>那这个数相当于基数和10^exp的乘积</p>
<ul>
<li>1.25e2 表示 1.25 × 10^2等于 125.0。</li>
<li>1.25e-2 表示 1.25 × 10^-2等于 0.0125。</li>
</ul>
<p>如果一个十六进制数的指数为<code>exp</code>那这个数相当于基数和2^exp的乘积</p>
<ul>
<li>0xFp2 表示 15 × 2^2等于 60.0。</li>
<li>0xFp-2 表示 15 × 2^-2等于 3.75。</li>
</ul>
<p>下面的这些浮点原始值都等于十进制的<code>12.1875</code></p>
<pre><code>let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
</code></pre><p>数值类原始值可以包括额外的格式来增强可读性。整数和浮点数都可以添加额外的零并且包含下划线,并不会影响原始值:</p>
<pre><code>let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
</code></pre><h2 id="-">数值类型转换</h2>
<p>通常来讲,即使代码中的整数常量和变量已知非负,也请使用<code>Int</code>类型。总是使用默认的整数类型可以保证你的整数常量和变量可以直接被复用并且可以匹配整数类原始值的类型推测。
只有在必要的时候才使用其他整数类型,比如要处理外部的长度明确的数据或者为了优化性能、内存占用等等。使用显式指定长度的类型可以及时发现值溢出并且可以暗示正在处理特殊数据。</p>
<h3 id="-">整数转换</h3>
<p>不同整数类型的变量和常量可以存储不同大小的数字。<code>Int8</code>类型的常量或者变量可以存储的数字范围是<code>-128</code>~<code>127</code><code>UInt8</code>类型的常量或者变量能存储的数字范围是<code>0</code>~<code>255</code>。如果数字超出了常量或者变量可存储的范围,编译的时候会报错:</p>
<pre><code>let cannotBeNegative: UInt8 = -1
// UInt8 类型不能存储负数,所以会报错
let tooBig: Int8 = Int8.max + 1
// Int8 类型不能存储超过最大值的数,所以会报错
</code></pre><p>因为每一个整数类型都可以存储不同范围的值,你必须根据情况来选择不同的转换方法。不同的转换方法可以暴露出隐藏的转换错误并让你的代码更加清晰。</p>
<p>要将一种数字类型转换成另一种,你要用当前值来初始化一个新数字,这个数字的类型就是你的目标类型。在下面的例子中,常量<code>twoThousand</code>类型是<code>UInt16</code>,然而常量<code>one</code>类型是<code>Uint8</code>。它们不能直接相加,因为它们类型不同。所以要调用<code>UInt16(one)</code>来创建一个新的<code>UInt16</code>数字并用<code>one</code>的值来初始化,然后使用这个新数字来计算:</p>
<pre><code>let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
</code></pre><p>现在两个数字的类型都是<code>UInt16</code>,可以进行相加。目标常量<code>twoThousandAndOne</code>的类型被推测为<code>UInt16</code>,因为它是两个<code>UInt16</code>值的合。</p>
<p><code>SomeType(ofInitialValue)</code>是调用 Swift 构造器并传入一个初始值的默认方法。在语言内部,<code>UInt16</code>有一个构造器,可以接受一个<code>UInt8</code>类型的值,所以这个构造器可以用现有的<code>UInt8</code>来创建一个新的<code>UInt16</code>。注意,你并不能传入任意类型的值,只能传入<code>UInt16</code>内部有对应构造器的值。不过你可以扩展现有的类型来让它可以接收其他类型的值(包括自定义类型),详情参见<code>扩展(链接待添加)</code>.</p>
<h3 id="-">整数和浮点数转换</h3>
<p>整数和浮点数的转换必须显式指定类型:</p>
<pre><code>let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi 等于 3.14159,所以被推测为 Double 类型
</code></pre><p>这个例子中,常量<code>three</code>的值被用来创建一个<code>Double</code>类型的值,所以加号两边的数类型相同。如果不进行转换,两者无法相加。</p>
<p>浮点数转换为整数也一样,整数类型可以用<code>Double</code>或者<code>Float</code>类型来初始化:</p>
<pre><code>let integerPi = Int(pi)
// integerPi 等于 3所以被推测为 Int 类型
</code></pre><p>当用这种方式来初始化一个新的整数值时,浮点值会被截断。也就是说<code>4.75</code>会变成<code>4</code><code>-3.9</code>会变成<code>3</code></p>
<blockquote>
<p>注意:结合数字类常量和变量不同于结合数字类原始值。原始值<code>3</code>可以直接和原始值<code>0.14159</code>相加,因为数字原始值本身没有明确的类型。它们的类型只在编译器需要求值的时候被推测。</p>
</blockquote>
</section>
</div>
</div>
</div>
<a href="../chapter2/chapter2.html" class="navigation navigation-prev " aria-label="Previous page: Swift 教程"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/02_Basic_Operators.html" class="navigation navigation-next " aria-label="Next page: 基本操作符"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
</body>
</html>