Files
the-swift-programming-langu…/chapter3/03_Types.html
2014-06-09 22:19:55 +08:00

847 lines
46 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="../chapter3/04_Expressions.html" />
<link rel="prev" href="../chapter3/02_Lexical_Structure.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="3.3" data-basepath=".." data-revision="1402323563628">
<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/10_Statements.html">
<a href="../chapter3/10_Statements.html">
<i class="fa fa-check"></i> <b>3.5.</b> 语句
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.6.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.7.</b> 特性
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.8.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.9" 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.9.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.10" 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.10.</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>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></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: 84.21052631578948%;min-width: 81.57894736842105%;"></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.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter done " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter done " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="嵌套类型" class="chapter done " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter done " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter done " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter done " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter done " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter done " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter done " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter done " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter done " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter done " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter done " data-progress="2.7" style="left: 65.78947368421052%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter done " data-progress="2.8" style="left: 68.42105263157895%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter done " data-progress="2.9" style="left: 71.05263157894737%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter done new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter done " data-progress="3.1" style="left: 76.3157894736842%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter done " data-progress="3.10" style="left: 78.94736842105263%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter done " data-progress="3.2" style="left: 81.57894736842105%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter done " data-progress="3.3" style="left: 84.21052631578948%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.84210526315789%;"></a>
<a href="../chapter3/10_Statements.html" title="语句" class="chapter " data-progress="3.5" style="left: 89.47368421052632%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.6" style="left: 92.10526315789474%;"></a>
<a href="../chapter3/06_Attributes.html" title="特性" class="chapter " data-progress="3.7" style="left: 94.73684210526316%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.8" style="left: 97.36842105263158%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_328">
<h1 id="-types-">类型Types</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li>类型标注Type Annotation</li>
<li>类型标识符Type Identifier</li>
<li>元组类型Tuple Type</li>
<li>函数类型Function Type</li>
<li>数组类型Array Type</li>
<li>可选类型Optional Type</li>
<li>隐式解析可选类型Implicitly Unwrapped Optional Type</li>
<li>协议合成类型Protocol Composition Type</li>
<li>元类型Metatype Type</li>
<li>类型继承子句Type Inheritance Clause</li>
<li>类型推断Type Inference</li>
</ul>
<p>Swift语言存在两种类型命名型类型和复合型类型。<em>命名型类型</em>是指定义时可以给定名字的类型。命名型类型包括类、结构体、枚举和协议。比如,一个用户定义的类<code>MyClass</code>的实例拥有类型<code>MyClass</code>。除了用户定义的命名型类型Swift标准库也定义了很多常用的命名型类型包括那些表示数组、字典和可选值的类型。</p>
<p>那些通常被其它语言认为是基本或初级的数据型类型Data types——比如表示数字、字符和字符串——实际上就是命名型类型Swift标准库是使用结构体定义和实现它们的。因为它们是命名型类型因此你可以按照“扩展和扩展声明”章节里讨论的那样声明一个扩展来增加它们的行为以适应你程序的需求。</p>
<p><em>复合型类型</em>是没有名字的类型它由Swift本身定义。Swift存在两种复合型类型函数类型和元组类型。一个复合型类型可以包含命名型类型和其它复合型类型。例如元组类型<code>(Int, (Int, Int))</code>包含两个元素:第一个是命名型类型<code>Int</code>,第二个是另一个复合型类型<code>(Int, Int)</code>.</p>
<p>本节讨论Swift语言本身定义的类型并描述Swift中的类型推断行为。</p>
<blockquote>
<p>类型的语法:
<em>type</em><em>array-type</em> | <em>function-type</em> | <em>type-identifier</em> | <em>tuple-type</em> | <em>optional-type</em> | <em>implicitly-unwrapped-optional-type</em> | protocol-composition-type | metatype-type</p>
</blockquote>
<h2 id="-">类型标注</h2>
<p>类型标注显式地指定一个变量或表达式的值。类型标注始于冒号<code>:</code>终于类型,比如下面两个例子:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> someTuple(Double, Double) = (<span class="hljs-number">3.14159</span>, <span class="hljs-number">2.71828</span>)
func someFunction(a: Int){ <span class="hljs-comment">/* ... */</span> }
</code></pre>
<p>在第一个例子中,表达式<code>someTuple</code>的类型被指定为<code>(Double, Double)</code>。在第二个例子中,函数<code>someFunction</code>的参数<code>a</code>的类型被指定为<code>Int</code></p>
<p>类型标注可以在类型之前包含一个类型特性type attributes的可选列表。</p>
<blockquote>
<p>类型标注的语法:
<em>type-annotation</em> → :<em>attributes</em>[opt] <em>type</em></p>
</blockquote>
<h2 id="-">类型标识符</h2>
<p>类型标识符引用命名型类型或者是命名型/复合型类型的别名。</p>
<p>大多数情况下,类型标识符引用的是同名的命名型类型。例如类型标识符<code>Int</code>引用命名型类型<code>Int</code>,同样,类型标识符<code>Dictionary&lt;String, Int&gt;</code>引用命名型类型<code>Dictionary&lt;String, Int&gt;</code></p>
<p>在两种情况下类型标识符引用的不是同名的类型。情况一,类型标识符引用的是命名型/复合型类型的类型别名。比如,在下面的例子中,类型标识符使用<code>Point</code>来引用元组<code>(Int, Int)</code></p>
<pre><code class="lang-javascript">typealias Point = (Int, Int)
<span class="hljs-keyword">let</span> origin: Point = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
</code></pre>
<p>情况二类型标识符使用dot(<code>.</code>)语法来表示在其它模块modules或其它类型嵌套内声明的命名型类型。例如下面例子中的类型标识符引用在<code>ExampleModule</code>模块中声明的命名型类型<code>MyType</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> someValue: ExampleModule.MyType
</code></pre>
<blockquote>
<p>类型标识符的语法:
<em>type-identifier</em><em>type-name generic-argument-clause</em>[opt] | <em>type-name generic-argument-clause</em>[opt].<em>type-identifier</em>
<em>type-name</em><em>identifier</em></p>
</blockquote>
<h2 id="-">元组类型</h2>
<p>元组类型使用逗号隔开并使用括号括起来的0个或多个类型组成的列表。</p>
<p>你可以使用元组类型作为一个函数的返回类型,这样就可以使函数返回多个值。你也可以命名元组类型中的元素,然后用这些名字来引用每个元素的值。元素的名字由一个标识符和<code>:</code>组成。“函数和多返回值”章节里有一个展示上述特性的例子。</p>
<p><code>void</code>是空元组类型<code>()</code>的别名。如果括号内只有一个元素,那么该类型就是括号内元素的类型。比如,<code>(Int)</code>的类型是<code>Int</code>而不是<code>(Int)</code>。所以,只有当元组类型包含两个元素以上时才可以标记元组元素。</p>
<blockquote>
<p>元组类型语法:
<em>tuple</em> → (<em>tuple-type-body</em>[opt])
<em>tuple-type-body</em><em>tuple-type-element-list</em> ...[opt]
<em>tuple-type-element-list</em><em>tuple-type-element</em> | <em>tuple-type-element</em>, <em>tuple-type-element-list</em>
<em>tuple-type-element</em><em>attributes</em>[opt] <strong>inout</strong> [opt] <em>type</em> | <strong>inout</strong> [opt] <em>element-name type-annotation</em>
<em>element-name</em><em>identifier</em></p>
</blockquote>
<h2 id="-">函数类型</h2>
<p>函数类型表示一个函数、方法或闭包的类型,它由一个参数类型和返回值类型组成,中间用箭头<code>-&gt;</code>隔开:</p>
<ul>
<li><code>parameter type</code> -&gt; <code>return type</code></li>
</ul>
<p>由于 <em>参数类型</em><em>返回值类型</em> 可以是元组类型,所以函数类型可以让函数与方法支持多参数与多返回值。</p>
<p>你可以对函数类型应用带有参数类型<code>()</code>并返回表达式类型的<code>auto_closure</code>属性(见类型属性章节)。一个自动闭包函数捕获特定表达式上的隐式闭包而非表达式本身。下面的例子使用<code>auto_closure</code>属性来定义一个很简单的assert函数</p>
<pre><code class="lang-javascript">func simpleAssert(condition: @auto_closure () -&gt; Bool, message: <span class="hljs-built_in">String</span>){
<span class="hljs-keyword">if</span> !condition(){
println(message)
}
}
<span class="hljs-keyword">let</span> testNumber = <span class="hljs-number">5</span>
simpleAssert(testNumber % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>, <span class="hljs-string">"testNumber isn't an even number."</span>)
<span class="hljs-comment">// prints "testNumber isn't an even number."</span>
</code></pre>
<p>函数类型可以拥有一个可变长参数作为参数类型中的最后一个参数。从语法角度上讲,可变长参数由一个基础类型名字和<code>...</code>组成,如<code>Int...</code>。可变长参数被认为是一个包含了基础类型元素的数组。即<code>Int...</code>就是<code>Int[]</code>。关于使用可变长参数的例子,见章节“可变长参数”。</p>
<p>为了指定一个<code>in-out</code>参数,可以在参数类型前加<code>inout</code>前缀。但是你不可以对可变长参数或返回值类型使用<code>inout</code>。关于In-Out参数的讨论见章节In-Out参数部分。</p>
<p>柯里化函数curried function的类型相当于一个嵌套函数类型。例如下面的柯里化函数<code>addTwoNumber()()</code>的类型是<code>Int -&gt; Int -&gt; Int</code></p>
<pre><code class="lang-javascript">func addTwoNumbers(a: Int)(b: Int) -&gt; Int{
<span class="hljs-keyword">return</span> a + b
}
addTwoNumbers(<span class="hljs-number">4</span>)(<span class="hljs-number">5</span>) <span class="hljs-comment">// returns 9</span>
</code></pre>
<p>柯里化函数的函数类型从右向左组成一组。例如,函数类型<code>Int -&gt; Int -&gt; Int</code>可以被理解为<code>Int -&gt; (Int -&gt; Int)</code>——也就是说,一个函数传入一个<code>Int</code>然后输出作为另一个函数的输入,然后又返回一个<code>Int</code>。例如,你可以使用如下嵌套函数来重写柯里化函数<code>addTwoNumbers()()</code></p>
<pre><code class="lang-javascript">func addTwoNumbers(a: Int) -&gt; (Int -&gt; Int){
func addTheSecondNumber(b: Int) -&gt; Int{
<span class="hljs-keyword">return</span> a + b
}
<span class="hljs-keyword">return</span> addTheSecondNumber
}
addTwoNumbers(<span class="hljs-number">4</span>)(<span class="hljs-number">5</span>) <span class="hljs-comment">// Returns 9</span>
</code></pre>
<blockquote>
<p>函数类型的语法:
<em>function-type</em><em>type</em> <strong>-&gt;</strong> <em>type</em></p>
</blockquote>
<h2 id="-">数组类型</h2>
<p>Swift语言使用类型名紧接中括号<code>[]</code>来简化标准库中定义的命名型类型<code>Array&lt;T&gt;</code>。换句话说,下面两个声明是等价的:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> someArray: <span class="hljs-built_in">String</span>[] = [<span class="hljs-string">"Alex"</span>, <span class="hljs-string">"Brian"</span>, <span class="hljs-string">"Dave"</span>]
<span class="hljs-keyword">let</span> someArray: <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">String</span>&gt; = [<span class="hljs-string">"Alex"</span>, <span class="hljs-string">"Brian"</span>, <span class="hljs-string">"Dave"</span>]
</code></pre>
<p>上面两种情况下,常量<code>someArray</code>都被声明为字符串数组。数组的元素也可以通过<code>[]</code>获取访问:<code>someArray[0]</code>是指第0个元素<code>“Alex”</code></p>
<p>上面的例子同时显示,你可以使用<code>[]</code>作为初始值构造数组,空的<code>[]</code>则用来来构造指定类型的空数组。</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> emptyArray: Double[] = []
</code></pre>
<p>你也可以使用链接起来的多个<code>[]</code>集合来构造多维数组。例如,下例使用三个<code>[]</code>集合来构造三维整型数组:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> array3D: Int[][][] = [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]], [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>], [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>]]]
</code></pre>
<p>访问一个多维数组的元素时,最左边的下标指向最外层数组的相应位置元素。接下来往右的下标指向第一层嵌入的相应位置元素,依次类推。这就意味着,在上面的例子中,<code>array3D[0]</code>是指<code>[[1, 2], [3, 4]]</code><code>array3D[0][1]</code>是指<code>[3, 4]</code><code>array3D[0][1][1]</code>则是指值<code>4</code></p>
<p>关于Swift标准库中<code>Array</code>类型的细节讨论见章节Arrays。</p>
<blockquote>
<p>数组类型的语法:
<em>array-type</em><em>type</em><code>[ ]</code> | <em>array-type</em><code>[ ]</code></p>
</blockquote>
<h2 id="-">可选类型</h2>
<p>Swift定义后缀<code>?</code>来作为标准库中的定义的命名型类型<code>Optional&lt;T&gt;</code>的简写。换句话说,下面两个声明是等价的:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> optionalInteger: Int?
<span class="hljs-keyword">var</span> optionalInteger: Optional&lt;Int&gt;
</code></pre>
<p>在上述两种情况下,变量<code>optionalInteger</code>都被声明为可选整型类型。注意在类型和<code>?</code>之间没有空格。</p>
<p>类型<code>Optional&lt;T&gt;</code>是一个枚举,有两种形式,<code>None</code><code>Some(T)</code>,又来代表可能出现或可能不出现的值。任意类型都可以被显式的声明(或隐式的转换)为可选类型。当声明一个可选类型时,确保使用括号给<code>?</code>提供合适的作用范围。比如说,声明一个整型的可选数组,应写作<code>(Int[])?</code>,写成<code>Int[]?</code>的话则会出错。</p>
<p>如果你在声明或定义可选变量或特性的时候没有提供初始值,它的值则会自动赋成缺省值<code>nil</code></p>
<p>可选符合<code>LogicValue</code>协议,因此可以出现在布尔值环境下。此时,如果一个可选类型<code>T?</code>实例包含有类型为<code>T</code>的值(也就是说值为<code>Optional.Some(T)</code>),那么此可选类型就为<code>true</code>,否则为<code>false</code></p>
<p>如果一个可选类型的实例包含一个值,那么你就可以使用后缀操作符<code>!</code>来获取该值,正如下面描述的:</p>
<pre><code class="lang-javascript">optionalInteger = <span class="hljs-number">42</span>
optionalInteger! <span class="hljs-comment">// 42</span>
</code></pre>
<p>使用<code>!</code>操作符获取值为<code>nil</code>的可选项会导致运行错误runtime error</p>
<p>你也可以使用可选链和可选绑定来选择性的执行可选表达式上的操作。如果值为<code>nil</code>,不会执行任何操作因此也就没有运行错误产生。</p>
<p>更多细节以及更多如何使用可选类型的例子,见章节“可选”。</p>
<blockquote>
<p>可选类型语法:
<em>optional-type</em><em>type</em>?</p>
</blockquote>
<h2 id="-">隐式解析可选类型</h2>
<p>Swift语言定义后缀<code>!</code>作为标准库中命名类型<code>ImplicitlyUnwrappedOptional&lt;T&gt;</code>的简写。换句话说,下面两个声明等价:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> implicitlyUnwrappedString: <span class="hljs-built_in">String</span>!
<span class="hljs-keyword">var</span> implicitlyUnwrappedString: ImplicitlyUnwrappedOptional&lt;<span class="hljs-built_in">String</span>&gt;
</code></pre>
<p>上述两种情况下,变量<code>implicitlyUnwrappedString</code>被声明为一个隐式解析可选类型的字符串。注意类型与<code>!</code>之间没有空格。</p>
<p>你可以在使用可选的地方同样使用隐式解析可选。比如,你可以将隐式解析可选的值赋给变量、常量和可选特性,反之亦然。</p>
<p>有了可选,你在声明隐式解析可选变量或特性的时候就不用指定初始值,因为它有缺省值<code>nil</code></p>
<p>由于隐式解析可选的值会在使用时自动解析,所以没必要使用操作符<code>!</code>来解析它。也就是说,如果你使用值为<code>nil</code>的隐式解析可选,就会导致运行错误。</p>
<p>使用可选链会选择性的执行隐式解析可选表达式上的某一个操作。如果值为<code>nil</code>,就不会执行任何操作,因此也不会产生运行错误。</p>
<p>关于隐式解析可选的更多细节,见章节“隐式解析可选”。</p>
<blockquote>
<p>隐式解析可选的语法:
implicitly-unwrapped-optional-type → type!</p>
</blockquote>
<h2 id="-">协议合成类型</h2>
<p>协议合成类型是一种符合每个协议的指定协议列表类型。协议合成类型可能会用在类型标注和泛型参数中。</p>
<p>协议合成类型的形式如下:</p>
<pre><code class="lang-javascript">protocol&lt;Protocol <span class="hljs-number">1</span>, Procotol <span class="hljs-number">2</span>&gt;
</code></pre>
<p>协议合成类型允许你指定一个值,其类型可以适配多个协议的条件,而且不需要定义一个新的命名型协议来继承其它想要适配的各个协议。比如,协议合成类型<code>protocol&lt;Protocol A, Protocol B, Protocol C&gt;</code>等效于一个从<code>Protocol A</code><code>Protocol B</code> <code>Protocol C</code>继承而来的新协议<code>Protocol D</code>,很显然这样做有效率的多,甚至不需引入一个新名字。</p>
<p>协议合成列表中的每项必须是协议名或协议合成类型的类型别名。如果列表为空,它就会指定一个空协议合成列表,这样每个类型都能适配。</p>
<blockquote>
<p>协议合成类型的语法:
<em>protocol-composition-type</em><strong>protocol</strong> &lt;<em>protocol-identifier-list[opt]</em>&gt;
<em>protocol-identifier-list</em><em>protocol-identifier</em> | <em>protocol-identifier, protocol-identifier-list</em>
<em>protocol-identifier</em><em>type-identifier</em></p>
</blockquote>
<h2 id="-">元类型</h2>
<p>元类型是指所有类型的类型,包括类、结构体、枚举和协议。</p>
<p>类、结构体或枚举类型的元类型是相应的类型名紧跟<code>.Type</code>。协议类型的元类型——并不是运行时适配该协议的具体类型——是该协议名字紧跟<code>.Protocol</code>。比如,类<code>SomeClass</code>的元类型就是<code>SomeClass.Type</code>,协议<code>SomeProtocol</code>的元类型就是<code>SomeProtocal.Protocol</code></p>
<p>你可以使用后缀<code>self</code>表达式来获取类型。比如,<code>SomeClass.self</code>返回<code>SomeClass</code>本身,而不是<code>SomeClass</code>的一个实例。同样,<code>SomeProtocol.self</code>返回<code>SomeProtocol</code>本身,而不是运行时适配<code>SomeProtocol</code>的某个类型的实例。还可以对类型的实例使用<code>dynamicType</code>表达式来获取该实例在运行阶段的类型,如下所示:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">class</span> SomeBaseClass {
<span class="hljs-keyword">class</span> func printClassName() {
println(<span class="hljs-string">"SomeBaseClass"</span>)
}
}
<span class="hljs-keyword">class</span> SomeSubClass: SomeBaseClass {
override <span class="hljs-keyword">class</span> func printClassName() {
println(<span class="hljs-string">"SomeSubClass"</span>)
}
}
<span class="hljs-keyword">let</span> someInstance: SomeBaseClass = SomeSubClass()
<span class="hljs-comment">// someInstance is of type SomeBaseClass at compile time, but</span>
<span class="hljs-comment">// someInstance is of type SomeSubClass at runtime</span>
someInstance.dynamicType.printClassName()
<span class="hljs-comment">// prints "SomeSubClass</span>
</code></pre>
<blockquote>
<p>元类型的语法:
<em>metatype-type</em><em>type</em>.<strong>Type</strong> | <em>type</em>.<strong>Protocol</strong></p>
</blockquote>
<h2 id="-">类型继承子句</h2>
<p>类型继承子句被用来指定一个命名型类型继承哪个类且适配哪些协议。类型继承子句开始于冒号<code>:</code>,紧跟由<code>,</code>隔开的类型标识符列表。</p>
<p>类可以继承单个超类,适配任意数量的协议。当定义一个类时,超类的名字必须出现在类型标识符列表首位,然后跟上该类需要适配的任意数量的协议。如果一个类不是从其它类继承而来,那么列表可以以协议开头。关于类继承更多的讨论和例子,见章节“继承”。</p>
<p>其它命名型类型可能只继承或适配一个协议列表。协议类型可能继承于其它任意数量的协议。当一个协议类型继承于其它协议时,其它协议的条件集合会被集成在一起,然后其它从当前协议继承的任意类型必须适配所有这些条件。</p>
<p>枚举定义中的类型继承子句可以是一个协议列表,或是指定原始值的枚举,一个单独的指定原始值类型的命名型类型。使用类型继承子句来指定原始值类型的枚举定义的例子,见章节“原始值”。</p>
<blockquote>
<p>类型继承子句的语法:
<em>type-inheritance-clause</em> → :<em>type-inheritance-list</em>
<em>type-inheritance-list</em><em>type-identifier</em> | <em>type-identifier</em>, <em>type-inheritance-list</em></p>
</blockquote>
<h2 id="-">类型推断</h2>
<p>Swift广泛的使用类型推断从而允许你可以忽略很多变量和表达式的类型或部分类型。比如对于<code>var x: Int = 0</code>,你可以完全忽略类型而简写成<code>var x = 0</code>——编译器会正确的推断出<code>x</code>的类型<code>Int</code>。类似的,当完整的类型可以从上下文推断出来时,你也可以忽略类型的一部分。比如,如果你写了<code>let dict: Dictionary = [&quot;A&quot;: 1]</code>,编译提也能推断出<code>dict</code>的类型是<code>Dictionary&lt;String, Int&gt;</code></p>
<p>在上面的两个例子中类型信息从表达式树expression tree的叶子节点传向根节点。也就是说<code>var x: Int = 0</code><code>x</code>的类型首先根据<code>0</code>的类型进行推断,然后将该类型信息传递到根节点(变量<code>x</code>)。</p>
<p>在Swift中类型信息也可以反方向流动——从根节点传向叶子节点。在下面的例子中常量<code>eFloat</code>上的显式类型标注(<code>:Float</code>)导致数字字面量<code>2.71828</code>的类型是<code>Float</code>而非<code>Double</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> e = <span class="hljs-number">2.71828</span> <span class="hljs-comment">// The type of e is inferred to be Double.</span>
<span class="hljs-keyword">let</span> eFloat: Float = <span class="hljs-number">2.71828</span> <span class="hljs-comment">// The type of eFloat is Float.</span>
</code></pre>
<p>Swift中的类型推断在单独的表达式或语句水平上进行。这意味着所有用于推断类型的信息必须可以从表达式或其某个子表达式的类型检查中获取。</p>
</section>
</div>
</div>
</div>
<a href="../chapter3/02_Lexical_Structure.html" class="navigation navigation-prev " aria-label="Previous page: 词法结构"><i class="fa fa-angle-left"></i></a>
<a href="../chapter3/04_Expressions.html" class="navigation navigation-next " aria-label="Next page: 表达式"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/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>